Skip to main content
Engineering LibreTexts

3.3: Events, Onload Event and JQuery

  • Page ID
    27547
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    One important paradigm that is implemented in JavaScript is Event Based Programming (EBP). Events are asynchronous actions that occur (or are raised) while the program is running. These actions (or events) are often generated by the user, such as clicking a button or changing the value in a text field. But events can also occur from asynchronous action of the program, such as loading the web page or the completion of reading of a file. The events which are raised are then associated with a callback function that handles the event.

    3.3.1 Associating a call back with an event

    Associating a call back with an event is illustrated in the following program.

    Program 52 - Using a form element in the head before it is defined.
    
    <html>
        <head>
            <title>Error using event </title>
            <script>
                function pressFunction() {
                    alert("You pressed me");
                        //document.write("You pressed me");
                };        
            </script>
        </head>
        
        <body>
            <input type="button"  value="Press me"
                onClick="pressFunction();"/>
        </body>
    </html>                        
    

    In this example, the click event (called onClick) is associated with the function pressFunction, which is metadata and defined in the head of the html page. When a user clicks on the button that says, “Press me”, it calls the function associated with the click even, the pressFunction, and an alert box is shown saying “You pressed me”.

    This is the complete life cycle of events and call backs. An event (click) is mapped to a callback function (pressFunction). When the event is raised (the user clicks the button), the event call back function is called.

    The rest of this section will explain how you should implement these in JavaScript.

    3.3.2 Handling an Event – Unobtrusive JavaScript

    Because event (or callback) functions are run in response to events from the program, they are metadata. This implies that when writing an HTML page, it is normal for a programmer to define functions to handle events coming from form elements in the head of the html document. A standard know as Unobtrusive JavaScript says that all JavaScript should be maintained in the head of the document, so setting the onClick as part of the button definition is considered bad practice.

    The correct way to assign a callback function is as follows. First it is important to know that all components on a web page are contained in a Document Object Model, or DOM. The DOM is very important when writing JavaScript for a browser, as nearly everything is in the DOM. However, for now you should know that buttons, text fields, checkboxes, etcetera, are all stored as objects in the DOM.

    Unobtrusive JavaScript says that the call back should be assigned by retrieving the button, in this case the button named “myButton” from the DOM using the getElementById method. The click event for this button is then assigned to an anonymous function which is then called when the button is pressed. This is shown in Program 53 below.

    Program 53 - Using a form element in the head before it is defined.
    
    <html>
        <head>
            <title>Error using event </title>
            <script>
                document.getElementById("myButton").click = function() {
                    alert("You pressed me");
                };
            </script>
        </head>
        
        <body>
            <input type="button"  value="Press me" />
        </body>
    </html>                                            
    

    However, there is a problem with this program. The form elements, such as a button, are defined in the body of the page, and that is after the attempt to use it to set its callback occurs in the head. As the following JavaScript program shows, this results in an error when trying to reference the button before it is defined. Note this error occurs in the browser console, which is not directly viewable to the user. If you do not know how to use the browser console, you should Google how to access it for the browser you are using (accessing the console is different for every browser, but is available in every browser).

    Figure 4 - Error message processing a form element before it is defined

    Screen Shot 2020-07-03 at 10.57.02 PM.png

    How to handle this problem will be the subject of the next section.

    3.3.3 Handling an Event – onload event

    To handle the problem of needing to access the button in the head, an event is defined that is raised after the form is loaded, and all form elements are defined. This event is called an onLoad event. The onLoad event occurs after the form is loaded, and thus after all the form elements have been processed and are available to be referenced. A callback function attached to the onLoad event can safely reference form elements in the body, knowing that the form is completely loaded, and the body of the HTML file is processed. This is shown in the following example.

    Program 54 - Setting a callback function in an onLoad event
    
    <html>
        <head>
            <title>Using onLoad event </title>
        <script>
            function myOnLoad() {
                document.getElementById("myButton").onclick = function() {
                    alert("You pressed me");
                }
            }
            window. Onload = myOnLoad;
        </script>
        </head>
        
        <body>
            <input type="button"  value="Press me" />
        </body>
    </html>                
    

    This small piece of code is complex, so it will be covered in some detail here. First a function, myOnLoad is defined, and it is in this function that the myButton’s click event is associated with the function to alert the user. The function myOnLoad is not called, so it is defined but not yet executed.

    The next line of code, window.onload = myOnLoad, associates the myOnLoad method with the onLoad event. This tells the HTML DOM to run the myOnLoad function when the onLoad event is raised, after the page is loaded. This means that the button myButton has been defined and can be associated with the listener to alert a message when the button is pressed. This part is fairly simple, at least in a big picture sense, to understand.

    What is much more complex is that the function myOnLoad is not called in the statement window.onload = myOnLoad, but the function is assigned to the variable window.onload and called later when the onLoad event is raised. To see this, compare the previous program with the next program, which includes the parenthesis in the assignment of the window.onload variable. This is a common mistake by novice programmers, as most novices have been taught that functions are executable statements that are run, and not data that can be passed around using variables.

    Program 55 - Program showing function being called rather than being set to a variable.
    
    <html>
        <head>
            <title>Window onload event</title>
            <script>
                function myOnload() {
                    /* This code causes the JavaScript to fail if
                       uncommented. But it would not work anyway as the
                       button code has not been loaded...
                    document.getElementById("myButton").onclick = function() {
                       alert("You pressed me");
                    }
                    */
                    alert("window is not loaded");
                    return "you dummy";
                }
                alert(window.onload = myOnload());
            </script>
        </head>
        
        <body>
        </body>
    </html>           
    

    The result of this second program is that the alert is run once when the head of the HTML file is processed, and the window.onload variable is set to the string “you dummy”, which is what is returned from the myOnLoad function. Once again, you cannot associate the button with a function as the button would not exist. The code to associate a function with an event must be run in the onLoad event, not when the head of the HTML file is processed.

    Before continuing, the reader should note that if a function is referenced without parenthesis (e.g. myOnLoad) the function is treated as data. If a function is referenced with parenthesis (e.g. myOnLoad()), the function is executed. From a syntactic point of view, this is probably the issue that causes the most problems to novice JavaScript programmers.

    This example shows an important feature of JavaScript. Functions in JavaScript are treated as first class object and can be used like any other data type. Functions that can be used as data are called a Lambda functions. Lambda functions are the basis for a programming paradigm called Functional Programming, which is a very different paradigm from Procedural or Object-Oriented Programming. Even in languages that purport to have included lambda functions, like Java, are actually providing syntactic sugar for other language constructs, and languages like Java do not provide a real basis for Functional Programming.

    Note that since functions can be data, they can be passed as data values. This, in this program, the programmer has realized that the myOnload() function is likely never used in the program except in response to an onLoad event. There is really no need to clutter the JavaScript namespace with the name of the function, and the function is defined anonymously. This is the normal way the event callback is defined using an anonymous lambda function.

    Program 56 - Setting an event callback function using an anonymous function.
    
    <html>
        <head>
            <title>Using onLoad event </title>
            <script>
    
                window.onload = function() {
                    document.getElementById("myButton").onclick = function() {
                        alert("You pressed me");
                    };
                }
            </script>
        </head>
        
        <body>
            <input type="button"  value="Press me" />
        </body>
    </html>                                
    

    Here the variable is set in the same statement as the function defined.

    Note that the parentheses here do not mean the function is being executed but are part of the function definition. Once again this is confusing to novices learning JavaScript. To execute this function, the statement windows.onload=function(){...}() would have to be used. This will form the basis for another JavaScript paradigm to be introduced later, the Immediate-Invoked- Function-Expression (IIFE).

    3.3.4 JQuery ready function

    JQuery is a library that provides many functions which are useful when doing JavaScript programming. This text will use JQuery extensively. This is because JQuery provides so many useful features. Also, many of the examples of JavaScript programming found on the internet use it, and it is hard to read JavaScript examples on the web without knowing the basic concepts of JQuery.

    To use JQuery, the following line should be included in the head of your HTML document before any JQuery function is used. This line includes the JQuery library and gives the HTML document access to all JQuery utility. It must be included before any other libraries that might use JQuery.

    <script src=""https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>

    Once installed, JQuery statements are formatted as $(identifier). In this statement, the $ is short for the jQuery function, and so is just shorthand for saying jQuery(identifier).

    The identifier can be one of many different types of HTML elements, such as a CSS selector, JavaScript elements, element arrays, objects, selections, or other types of elements. JQuery will look at the element that is being requested and call a function that will perform the correct operation for that type20.

    In this section, only the JQuery options needed to assign the button onClick event will be covered. This will be done in two steps. The first will be how to handle the form loading in JQuery. The second will be how to set the onClick event for a button.

    The JQuery function that is run after the HTML file has completed processing and all form elements are defined is the $(document).ready() function. The $(document).ready() function is similar to setting a function in the window.onload event, and for the purpose here will be used interchangeably.

    The following code can be used to print a message to an alert box after the form elements have been processed. Note here that an event is not set to a function to execute, but the $(document).ready() function is executed when the HTML file has loaded. This is just a different way to handle the semantics of events. JavaScript will set a function to an event variable, and JQuery will call a method when the event is raised. Do not let this confuse you, as the effect is the same as setting the event variable. The function is run when the event is raised.

    Program 57 - Using the JQuery $(document).ready() function
    
    <html>
        <head>
            <title>Window onload event</title>
        <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        </script>
        <script>
            $(document).ready(function() {
                alert("window is loaded");    
            });
        </script>
        </head>
        
        <body>
        </body>
    </html>
    

    As of JQuery 3.0, the $(document).ready() syntax has been deprecated, and the current recommended syntax for calling the ready function is to put the function to be run when the page is loaded as a parameter to the jQuery function. Remember that $ is the jQuery function, so

    $(function(){...})
    

    is the same as saying

    jQuery(function(){...})

    The jQuery function will recognize the parameter is a function and set it to respond to the ready event. This is only a syntax change to make the code shorter and maybe easier to understand. Just remember if a function is passed to the jQuery function, it is set to the JQuery ready event.

    Program 58 - JQuery 3.0 ready function
    
    <html>
        <head>
        <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js ">
        </script>
        <title>Window onload event</title>
        <script>
            $(function() {
                alert("window is loaded");
            })
        </script>
        </head>
        
        <body>
        </body>
    </html>                
    

    3.3.5 Using JQuery to access an DOM variable

    One of the big advantages to JQuery is that it has a library to provide shortcuts to accessing JavaScript variables. JQuery shortcuts allow the retrieving any DOM elements such as buttons, textboxes, etc., using a simplified format. The JavaScript function to retrieve a from element by its id, document.getElementById(“id”), can be written more simply as $(“#id”) in JQuery, as is shown in the program below. From now on, JQuery syntax will be used to retrieve DOM elements.

    Program 59 - Using JQuery to access a DOM variable
    
    <html>
        <head>
        <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        </script>
        <title>Window onload event</title>
        <script>
            $(function() {
                $("#myButton").click(function(){
                    alert("you pressed me")
                })
            })
        </script>
        </head>
        
        <body>
            <input type="button"  value="Press me" />
        </body>
    </html>                        
    

    In this example, the id of the button is prefaced by the “#” (hash) sign. JQuery can be used to access various types of identifiers (called selectors in CSS), and it uses the CSS conventions to specify the type of selector it is using. For example, to use a class selector, the “.” (dot) will be prepended to the id. The “#” (hash) means the name is to be used to access the variable. The types of variables that can be accessed correspond to their CSS definitions, and will be seen in more detail in the chapter on CSS.

    Also note that the name of the JQuery function to handle an onClick event is the click function and setting the event variable has been changed to a function call. Both renaming the event and changing the event to a function call are conventions followed in JQuery.

    3.3.6 Quick Check

    1. What is an event?
    2. What does it mean to say an “event is asynchronous”?
    3. How is EBP different from procedural programming, where all programs being in the main and proceed one statement after another.
    4. What is a Lambda Function?
    5. What is an onLoad event. How does assigning a function to an onLoad event differ from using the $(document).ready() JQuery function?
    6. What is the shorthand method to write the $(document).ready() JQuery function?
    7. How would you access an DOM variable named “myVariable” using JQuery?

    20 For more information on how JQuery works and the types that are accepted to the jQuery function, see http://api.jquery.com/jquery/.


    This page titled 3.3: Events, Onload Event and JQuery is shared under a CC BY license and was authored, remixed, and/or curated by Charles W. Kann III.

    • Was this article helpful?