Lessons menu
JavaScript - advanced - Lesson nr. 2
JavaScript functions
What this lesson is about?
In this lesson we will learn about functions in JavaScript. In every programming language there is an endeavor to reuse code - once written, we are able to reference it multiple times, to be transparent and readable. The introduction of functions helps us with those problems. We will learn why and when to use functions. 

What is a function?
A function is a collection of instructions, solving a problem/task. Functions have names and can be called/invoked from different parts of the file to execute the instructions included in it.

Why use functions?
  • We can write code once and reference it (use it) multiple times. This means reusing code once written.
  • By naming and placing functions properly (hinting at the resolved problem) we can improve the readability of the code. This can help when other people use our code or we need to change something.
  • By using data exchange (parameters) between functions and HTML code, we can create more broad codes – we can solve a problem in a more general way.

New HTML tags:
<script></script> - if we place JavaScript code inside of an HTML file, but outside of the HTML tags, we need to place it between <script></script> tags. This way we mark the code for the browser.

New events in this lesson:
onload – this event is perceived to happen when the document is loaded. This can be used to set initial values, timers etc.
onresize – this event can be used partially like the media queries (rules) we previously studied. This event can be used to react to resizing the browser window. This event is on the JavaScript event list with the others, but does not get triggered when added to an HTML tag. Please see the example and the addEventListener method.

New object in this lesson:
window – this object has the properties and methods related to the browser window.

New methods in this lesson:
setTimeout(function, milliseconds) – this method can be used to schedule the execution of a function based on the time elapsed.

addEventListener(‘the events name’, the functions name) – with this method we can pair events and functions from code – we do not need to write it in the HTML. This means that we can decide on creating such pairings related to other events happening. We use the one in the window class in this lesson, but we can add it from every HTML element.

alert("the text comes here") – this method is used to show an error message above the content of the window.

date() – date can be used as method to add the current timestamp to an HTML page.

New properties in this lesson:
innerWidth – this property contains the width of the current window (can be refered as window.innerWidth). It cannot be changed. Resizing from code needs other methods and it is not a good idea.

innerHeight – this property contains the height of the current window, like the previous attribute.

Guidance:
  •  Both of the methods alert and addEventListener, are methods of the window object, but this does not need to be mentioned when using them.
  • There can be more functions tied to one event, they need to be separated by a semicolon.


Example on a simple function:


In this example we use the function named change. The function contains the one statement we previously written in the HTML tag. We cannot use the this reference here, we did not talk about data exchange between the functions and HTML, so, we need to add an id to the button and search for it from the function to change the text on it.

The function’s name is followed by empty brackets – these are meant for the data exchange mentioned – we do not write anything in it, for now.

The instructions solving the problem intended for this function are in other type of brackets. These are all necessary elements.

We use the <script> tag to mark the code, and the name of the function to write it after the onclick event reference.

Example on timing:


In this example we use the onload event. It is mostly associated with the <body> tag.

The init function is started as the page loads. This function contains one statement: we schedule the change1 function to run 3 seconds after the loading of the page.

The change1 function changes the image shown, and schedules the change2 function to start in 3 seconds.

The change2 function changes back the picture, and then refer back to the change1 function.

This means that the two pictures will change every 3 seconds, until we leave the page.  


Example on listening for events and showing alert boxes:


In this example we use for the first time the addEventListener method. When the page is loaded the init function is called to pair the resize event of the window object to the function called write. The init function will be running this once, achieving his role.

After this every time we resize the window one (or more) alert boxes appear to let us know the event we waited for just happened. Alert boxes can be irritating so use them wisely.

Exercises
1. Modify the forms.html file:
Add a new section before the gallery and an identifier to it.
Add padding, text color, background-color and bottom margin to it.
The font size should be calculated related to the window size (expressed in vw).
When the page opens, add the current date in that newly added section and refresh it every second.
View the result
2. Modify the forms.html file:
Add a new section after the one from the previous exercise, to always show the size of the window and design it the same way as the previous section.

Inside of the new section, write Window’s width:, followed by a paragraph with an identifier and the same way for the window’s height too.

Add a new function to the onload event named size.

The size function should assign the write function to the resize event. Call the write function to show the original size of the window.

The write function, called only when resizing happens, should refresh the content of the two paragraphs created in this exercise.
View the result
Questionnaire
1. What is not true about functions?
2. How do we resolve to call the start function when the page is resized?
3. What happens if we pair the init() function below to the load event?
function init(){
             setTimeout(init, 5000);
             alert("Hi!");
}
4. The code below should change the Colored text to red if the button is clicked. Select the correct statement to complete the function.
<p id="t1">Colored text</p>
<button id="t2" onclick="init2()">Click!</button>
<script>
             function init2(){ … }
</script>
Exclamation mark This site is using cookies. By continuing to browse the site, you accept their use! I accept