Contents  >

4: Introduction to Functions

Learning Goals

At the end of this Tutorial you will be able to:

In this Tutorial you will meet the following terms:

Exercise Files

In this Tutorial you will work with the following web page:

Contents

Downloading your JavaScript exercise files

About functions in JavaScript

Rules for working with functions

How functions are called

Exercise 4.1: Creating a simple function

Working with event handlers

Working with event listeners

Exercise 4.2: Creating a simple event listener

Uploading your JavaScript exercise files to GitHub

Tutorial summary

Downloading your JavaScript exercise files

Follow these steps to download the exercise files for this JavaScript Tutorial:

  1. Download this compressed file:   js-exercises-4.zip
  2. Copy the ZIP file to your new websites/js-exercises sub-folder. Javascript
  3. Unzip the file.
  4. This creates a new sub-folder named js-exercises-4. Javascript
  5. You no longer need the downloaded ZIP file. So you can delete js-exercises-4.zip.

The complete sub-folder and file structure for this Tutorial is as shown below.

Javascript

Your exercise file is now ready for you to work with.

About functions in JavaScript

In all programming languages, a function is a block of code that performs a particular task. JavaScript functions typically have the following format.

function functionname() {
   first instruction;
   second instruction;
   and so on;
}

Below is an example of function that adds two numbers and displays the result in as dialog box.

/* Perform calculation with two numbers */
function addTwoNumbers() {
   let firstNumber= 12;
   let secondNumber= 36;
   let SumTotal=firstNumber + secondNumber;
   window.alert(SumTotal);
}

Rules for working with functions

Before moving on let's review some important points about functions in JavaScript:

JavaScript functions are commonly placed at the bottom of a web page, just before the closing </body> tag.

Scattering lots of JavaScript functions at various locations in a web page, where they are mixed in with HTML tags and page content, results in a web page that is difficult to read and update.

How functions are called

Typically, functions do not run as soon as the web page loads in the visitor's web browser. Instead, most functions wait until they are called or invoked by some user action or event. More exactly, functions are invoked by one of the following two methods:

A typical sequence would be as follows:

Let's put together what you have learnt so far and create some simple functions.

Function

A named block of code that performs a particular action when called, typically by an event handler or event listener.

Exercise 4.1: Creating a simple function

In your websites/js-exercises/intro-functions sub-folder, open the following file in your VS Code and web browser:

exercise-4-1.html

In the empty <script> ... </script> tag pair at the bottom of the web page, just before the closing </body> tag. insert the following window.alert() statement.

function sayHello() {
    window.alert("Welcome to my web page.");
}

Your code should look as shown below.

Javascript

You are free to choose the function name. You could equally have named this function 'displayGreeting' or 'showFirsMessage' or whatever.

Save your web page and reload it in your web browser.

Notice that the dialog box with the greeting does not display on screen.

Is there an error in your function? No. Your function is code is valid. But it has no effect on the browser window because the function has not been called.

Leave the exercise-4-1.html file open in VS Code and your web browser. In the next section, you will add an event handler to your function.

Working with event handlers

A function within a web page waits there passively until it is called into action by an event handler. In the most typical case the user activates the event handler, and the event handler calls the function into action.

Three common events handlers are set out in the following table.

Event Handler

Description

onclick

This calls a function when the page visitor clicks once on an HTML element such as a button, image or item of text.

ondblclick

This calls a function when the page visitor clicks twice on an HTML element such as a button, image or item of text.

onmouseover

This calls a function when the page visitor holds the mouse pointer over an HTML element such as a button, image or item of text.

Event handlers are usually attached to buttons, but you can also link an event handler with an image or some text.

Event Handler

An HTML command in a web page that calls of triggers a function into action whenever a specific type of event is performed in or with the web page.

Let's add an event handler for your 'sayHello()' function in your exercise-4-1.html file.

In the file, inside the div with a class name of js-box, enter the HTML code and content for a button element.

 <button>Click to display greeting</button>

Note that this is not JavaScript. It's just HTML. It should look as shown below,

Javascript

Save the file. Reload it in your web browser. It should look similar to that below.

Javascript

Click the button. Does anything happen? No. You need to attach the button to your function with an event handler.

Update the button as shown below. And then save and reload the web page.

Javascript

Your button, when clicked, will now call the 'sayHello' JavaScript function. Success!

You can now close the exercise-4-1.html file.

Working with event listeners

An advantage of event listeners is that they too can be located tidily at the bottom of a web page rather than mixed in with the page content and HTML tags.

Before you can use an event listener, you give a unique ID to the button or other web page element that will call the function. The next exercise provides an example.

Exercise 4.2: Creating a simple event listener

In VS Code, open the file you worked on in the first exercise and save it with the new name of exercise-4-2.html.

Also display the new file in your web browser.

In the div with a class name of js-box, replace the current line with this new one.

<button id="btnGreeting">Click to display greeting</button>  

As you can see, you have removed the event handler named "sayHello()". You have also given a unique ID to the button of btnGreeting.

Next, in VS Code, scroll down the bottom of the web page and enter the following new line just above the function.

document.getElementById("btnGreeting").addEventListener("click", sayHello);

This is called an event listener, and 'connects' the button in the web page with the function that will be called when the button is clicked.

The complete code should look as follows.

Javascript

Save your file, reload it in your web browser, and click the button to verify that your JavaScript code words.

Uploading your JavaScript exercise files to GitHub

Follow these steps below to upload your entire js-exercises folder to your website on GitHub.

  1. Sign in to Github and click the name of the repository (‘repo’) that holds your web pages.
  2. On the next GitHub screen displayed, click the Add file button near the right of the screen and then choose Upload files from the dropdown list. github-upload-portfolio
  3. In File/Windows Explorer, select your js-exercises folder, and drag-and-drop it to your repository on GitHub. Introduction to Images
  4. Scroll down to the bottom of the GitHub screen, and accept or edit the short message (Add files via upload) in the Commit changes box.   Finally, click the green Commit changes button to upload your entire js-exercises folder and all the files it contains.

Your uploaded files are published on GitHub at a web address similar to the following, where username is the username you have chosen for your GitHub account:

https://username.github.io/js-exercises/js-exercises-4/intro-functions/exercise-4-1.html
https://username.github.io/js-exercises/js-exercises-4/intro-functions/exercise-4-2.html

It may take a few minutes for your uploaded files to appear on GitHub.

Tutorial summary

A function is a named script that performs a particular action when called or invoked.

Function names begin with the word 'function', must be unique in the web page, are case-sensitive and may not contain spaces. You can combine upper and lowercase letters in a function name to make it easier to read. Like methods, function names always end with a parenthesis.

Statements within a function are enclosed with curly braces { }, and are usually indented from the left to make them easier to read. A simple function is shown below.

/* Display an alert box with some welcome text */
function sayThankYou() {
    window.alert("Thanks for visiting my web page.");
}

JavaScript functions are commonly placed at the bottom of a web page, just before the closing </body> tag.

Functions can be called by event handlers positioned within a button or web page element. The event handler contains both the name of the function and type of user action or event that will call it. For example:

<button onclick="sayHello()">Click to display greeting</button>

A better, more modern approach is to call functions with event listeners, which can be located with functions at the bottom of a web page.

A button or other element that calls a function in this way contains an ID that links the calling element with the function. In the example below, clicking the button with an ID of 'btnGreeting' will call the function named 'sayHello()'.

document.getElementById("btnGreeting").addEventListener("click", sayHello);


Return to Contents.