Learn web design and programming with our free video and text tutorials.

Web Designer? Design and market your own professional website with easy-to-use tools.

Javascript Functions Tutorial

A javascript function is a block of code that will be executed by an event, or when the function is called.

Functions are declared with the "function" keyword followed by the function name. Paranthesis immediately follow the function name. The paranthesis contain the parameters of the function.

For example, the statement, function popup() declares a function named popup.

A function statement will be executed only when it is called, this is usefull when you do not want the web browser to execute to execute a javascript when the page loads.

A function can be called from anywhere within the <head> and <body> sections of a document, however, it is best to put functions in the <head> section so that they are read/loaded by the web browser before they are called.

A function can also be called when it is embedded in an external javascript (.js) file.

The rules for naming function names are the same as when naming javascript variables:

  • Variable names in javascript are case-sensitive. The variable names firstvariable, FirstVariable and FIRSTVARIABLE are all different.
  • Variable names must begin with a letter or the under-score character (_)

The code for the HTML file below contains a javascript function in the <head> section that will be called when the button is clicked.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<script type="text/javascript" language="javascript">
function popup()
alert("Hello World!");


<input type="button" onclick="popup()" value="Call function" />


Pressing the button below will call the function "popup".