Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Calling Functions

Code wrapped up in a function definition will not be executed when the page loads. Instead, it waits quietly until the function is called.

To call a function, you simply use the function name (with the parentheses) wherever you want to execute the statements contained in the function:


For example, you may want to add a call to your new function sayHello() to the onClick event of a button:

<input type="button" value="Say Hello" onclick="sayHello()" />

Putting JavaScript Code in the Page <head>

Up to now, our examples have all placed the JavaScript code into the <body> part of the HTML page. Using functions lets you employ the much more common, and usually preferable, practice of storing our JavaScript code in the <head> of the page. Functions contained within a <script> element in the page head, or in an external file included via the src attribute of a <script> element in the page head, are available to be called from anywhere on the page. Putting functions in the document’s head section ensures that they have been defined prior to any attempt being made to execute them.

Listing 3.1 has an example.

Listing 3.1. Functions in the Page Head

<!DOCTYPE html>
    <title>Calling Functions</title>
        function sayHello() {
    <input type="button" value="Say Hello" onclick="sayHello()" />

In this listing, you can see that the function definition itself has been placed inside a <script> element in the page head, but the call to the function has been made from a different place entirely—on this occasion, from the onClick event handler of a button in the body section of the page.

The result of clicking the button is shown in Figure 3.1.

Figure 3.1

Figure 3.1. Calling a JavaScript function

  • + Share This
  • 🔖 Save To Your Account