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.
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:
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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>
<script type="text/javascript" language="javascript">
function popup()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" onclick="popup()" value="Call function" />
</form>
</body>
</html>
Pressing the button below will call the function "popup".