Section 1: Introduction
Simple functions can be used to "package" multiple lines of JavaScript code, which makes it possible to execute those lines of code by invoking the function name.
The two examples below demonstrate the same code first without the use of functions, and then with the use of functions.
In this first example a few lines of JavaScript code are embedded in the line that instructs the browser how to handle the click of a particular button.
<html>
<head>
<title>MPH to KPH example with no functions</title>
</head>
<body>
<form>
<div>
<h1>MPH/KPH Converter</h1>
<div class="textHolder">
<label>Enter MPH:</label>
<input class="text" id="txtMPH" type="text" />
</div>
<div class="buttonHolder">
<input class="buttonLeft" name="cmdCalc" type="button"
onclick="document.getElementById('txtKPH').value=Math.round
((document.getElementById('txtMPH').value*1.609344)*100)/100;
document.getElementById('txtMPH').focus();"
value="Convert" />
<br />
</div>
<div class="textHolder">
<label>KPH:</label>
<input class="text" id="txtKPH" type="text" readonly="readonly"
/>
</div>
</div>
</form>
</body>
</html>
The second example shows the JavaScript code packaged as a function. Note that the code is easier to understand and the click event of the button is much less complex.
<html>
<head>
<title>MPH to KPH example with functions</title>
<script type="text/javascript">
function calcKM()
{
// declarations
var mph = 0;
var kph = 0;
const conversionFactor = 1.609344;
// input
mph = document.getElementById("txtMPH").value;
// processing
kph = mph * conversionFactor;
kph = Math.round(kph * 100) / 100;
// output
document.getElementById("txtKPH").value=kph;
}
</script>
</head>
<body>
<form>
<div>
<h1>MPH/KPH Converter</h1>
<div class="textHolder">
<label>Enter MPH:</label>
<input class="text" id="txtMPH" type="text" />
</div>
<div class="buttonHolder">
<input class="buttonLeft" name="cmdCalc" type="button"
onclick="calcKM();" value="Convert"
/>
<br />
</div>
<div class="textHolder">
<label>KPH:</label>
<input class="text" id="txtKPH" type="text" readonly="readonly"
/>
</div>
</div>
</form>
</body>
</html>
Note that the JavaScript could (and should) be placed in an external file, but early class examples include the JavaScript along with the html code to make it easier for students to view the JavaScript.
Section 2: Example
The previous demo includes a function used to convert miles per hour to kilometers per hour:
//------------------------------------------
// This function converts MPH to KPH. It expects the
// MPH value to be in an input field with the id txtMPH.
// It expects that the result will be placed in an input
// field with the id txtKPH.
//------------------------------------------
function convertMphToKph ()
{
// declarations
var mph = 0;
var kph = 0;
const conversionFactor = 1.609344;
// input
mph = document.getElementById("txtMPH").value;
// processing
kph = mph * conversionFactor;
kph = Math.round(kph * 100) / 100;
// output
document.getElementById("txtKPH").value=kph;
}
The function is invoked, or called, from the click event of the button labeled "Convert".
<input name="cmdCalc" type="button" value="Convert" onclick="convertMphToKph();" />
Note that the function is not very versatile as written.
- If you want to use the function in other web pages you must be sure that the fields are named "txtMPH" and "txtKPH" or you must edit the function each time you use it.
- We'll learn how to rectify that problem in a future example.
Section 3: Writing Functions
Functions must be declared before they can be used.
- For that reason, they are normally placed in the <head> tag of an HTML document to ensure that they are defined before use.
- The order in which they are declared is, however, irrelevant.
- They are enclosed in a <script> tag and can go anywhere in that tag.
Function declarations can also be placed in external JavaScript files.
Function Definition
The code representing the function is called the function definition.
function calcKM()
{
}
A function definition consists of a function header and a function body.
Function Header (simplified)
function function_name ( )
- The function header contains keyword function, the function name, and parentheses.
- All function definitions contain parentheses, which may be empty or may contain one or more parameter variable declarations (called a parameter list). [MORE LATER]
Function Body
Any declarations and statements the programmer places between the braces (or curly brackets) form the function body.
Execution of the function begins as soon as the function is called, and starts with the first line of code.
The function terminates when the closing brace is reached.
Section 4: Function Call
A function can be called directly from within a <script> tag, from a link, or called when an event is triggered, such as when the user clicks a button.
<input name="cmdCalc" type="button" onclick="calcKM();" value="Convert">
<script type="text/javascript">setFocus();alert('Set focus!');</script>