Home : Internet : JavaScript : Functions

JavaScript Functions

Functions are at the heart of JavaScript. Functions are a way of organising and controlling different sequences of code which work together with other functions, page elements and input from the user. A function typically contains a set of commands for a specific purpose which you want to run at a certain time.

Each function in a script is given a unique name. The example below is named "doSomething", although it could be given any name you like.

function doSomething() {
 // The function code goes here
}

The layout of a function always follows the same format, including these three things:

  1. The word "function"
  2. The function's name, followed by parentheses (which may or may not be empty)
  3. Curly braces containing the function's code

A script can contain any number of functions. For example, a script designed to check the contents of a form might have separate functions to check the username, password, email address, etc.


Calling a Function

Functions do not run automatically. When the page loads, each function waits quietly until it is told to run.

To run a function you must call it. This means sending an instruction to the function telling it to run. There are two common ways to call a function: From an event handler and from another function.

Calling a Function From an Event Handler

An event handler is a command which calls a function when an event happens, such as the user clicking a button. The command is written in the format onEvent, where Event is the name for a specific action. Here are some common examples:

User clicks a button (onClick):

<input type="button" value="Click Here" onClick="doSomething();">

User places their cursor in a text field (onFocus):

<input type="text" onFocus="doSomething();">

The page finishes loading (onLoad - this will run the function when the page loads, without any input from the user):

<body onLoad="doSomething();">

Calling a Function From Another Function

Functions can also call other functions. Simply enter the name of the function to be called, with its parentheses, like so:

function doSomething() {
  doSomethingElse();  // This line calls the next function
}

function doSomethingElse() {
  // The second function code goes here
}

Working Example

The example below creates a button with an onclick event. When the user clicks the button the function showAlert() is called. This particular function creates an alert message - click the button to demonstrate.

<script language="javascript" type="text/javascript">
function showAlert() {
 alert('Hello World - this is an alert message!');
}
</script>

<p><input type="button" value="Click here" onClick="showAlert();"></p>

Note: The onclick event can appear in the button tag without any accompanying script tag - the browser knows it is there to call a JavaScript function. The same applies to certain other form and page elements.


Remember:

Subscribe to us on YouTube