Universal Class: Over 500 Online Certificate Courses
A Closer Look at Event Handling in jQuery

A Closer Look at Event Handling in jQuery



Events are any functions triggered by input. Usually, events are based on user input, but other events are triggered during the life cycle of a web page such as when the page loads or the user leaves a page. In this article, we'll take a closer look at events and event handling.

Events Introduction

Events are triggered by the user, so they are associated with handlers that provide some kind of output for the user.  When the user clicks a button, a default event handler is used to determine what happens. If the button is associated with a form, the form submits to the server. If the button isn't associated with any custom handler or a form, nothing happens. The button element is often used to replace form submit buttons, so you see them more often than older HTML elements. They are just one element that works well with jQuery event handlers.

Buttons aren't the only elements that have events linked to them. When the page loads in a user's browser, the load event is triggered. When a user hovers a mouse icon over an element, the "mouse over" event is triggered. When the user removes the mouse cursor from hovering over an element, the "mouse out" event is triggered. When a key is pressed, the "key press" event is triggered.

As you can see, there are numerous events that link actions to triggers. A web page handles each event with a default action, but you can override this action with jQuery. This type of function override procedure is one of jQuery's main benefits. It lets you dynamically work with the user interface and control the input sent to the server and the output shown to your users.

When you work with web design and programming, you won't need to override every event trigger. You only need to work with the ones that will define the way your web page interacts with your user.

Another benefit of jQuery with HTML5 is that you can customize event handlers for each element. For instance, you can have eventhandler1 work with button1 and eventhandler2 work with button2. Both buttons trigger a click event, but you can tie an event handler with each one.

When you think of event handlers, always think of actions that happen on the page. They produce the output for your user. Output can be redirecting to another page, changing an image, editing text, or submitting a form. The event handler is your way of customizing these actions.

Load Events

A load event is exactly what it sounds like -- it's an event that triggers when an element loads. Every element on the page loads including the page itself. The "onload" event was commonly used to customize what happens to a web page when it loads in the user's browser. Now, jQuery can be used to customize the way any element loads in the page. This event is mainly used for images and forms to dynamically customize what displays when the user loads the page.

When you work with jQuery, you need to call the event and then define your custom function. So far, we've only used methods to change simple values and attributes. When you work with events and handlers, you create custom functions that handle actions.

Let's first take a look at an HTML element.


<div id="list"><p>This is a list of items</p></div>


The above HTML code is a simple div container that then has a paragraph child element with some text. When the user accesses your web page, this element has its own load event that you can override. Suppose you want to override the default text when the user is logged in and show the user's first name with a greeting. You can do this procedure on the backend or with jQuery.


$( "#list" ).load(function() {

  $("p").text("Hello, John");



In the above jQuery, we first use the div container's ID, which we've set as "list." We then call the load function. Notice that within the load function is another function. This statement tells the JavaScript engine that you want to customize the load event with your own function. The function always follows with open and closing parenthesis and then opening and closing brackets.

The statements within the function's opening and closing brackets are what happens when the event is triggered. In this example, the text within the paragraph tag is changed to "Hello, John."

You can use the load override functionality on any element. In this example, we just changed the paragraph's text, but you can have several lines of code in the function's definition. Just remember to always consider performance a priority. If you have several lines of code for your load functions, it takes that much longer for your pages to load before your users can interact with elements. Always take performance into consideration.

You can also trigger statements after the window completely loads including all elements on the page. The following jQuery code lets you run code after the entire window loads.


$( window ).load(function() {

 // custom code



Notice that "window" is not in quotes in the above statement, but the function syntax is still the same. The syntax to override any event is always the same.

Basic Events

The previous section just talked about the load event for each of your HTML elements, but several other events exist for each element including the DOM. This section will show you some of the main events you need to know when working with jQuery and your web pages.

The first common event is the blur event. Blur occurs when an element loses focus. It was originally commonly used with form elements, but it works with most elements on the page. The blue event triggers when an element loses focus. You would use this event for elements where the user clicks to interact with the page or sends input like typing a value. When the user clicks tab or another element, the element loses focus and the blur event is called.

You can raise the blur trigger as well when a user clicks another element. For instance, if the user doesn't fill out one of your form elements and clicks the submit button, you could then show an alert that tells the user to fill out the information.

The following code triggers the blue event when a user clicks a div container named "submit."


$( "#submit" ).click(function() {

 $( "#firstname" ).blur();


Interested in learning more? Why not take an online class in JQuery Programming?



The "change" event occurs when a user changes the selected value in a dropdown box. The following HTML is an example of a dropdown menu.


<select class="color">

    <option value="red" selected="selected">Red</option>

    <option value="blue">Blue</option>



The above dropdown menu shows the user two options: blue and red. The "Red" option is selected by default. When "Blue" is selected, the "change" event triggers. You can use jQuery to override what happens when the value selected changes. The following jQuery code overrides the event.


$( ".color" ).change(function() {

 alert( "The user changed the selected value." );



The alert only shows if the user changes the selection. If the same selection is chosen that is already selected, then the event is not triggered.

 What determines a click and a double-click is the user's operating system settings, but you can set your code to only trigger if the user double-clicks versus clicks. You can also set different event functions for click versus double-click.

You use the double-click event mostly on div containers set up to act as buttons or triggers to expand other menus. Take the following HTML for a clickable div container.


<div id="main">

 Double-click here.



The following jQuery code shows an alert when the user double-clicks but not single-clicks.


$( "#main" ).dblclick(function() {

 $("#main").text("The div was double-clicked");



You can override an event's default behavior using the "preventDefault" method. This is usually done to stop a form from submitting and the page reloading. You can stop the default action by overriding the standard event handler. The following jQuery code overrides the default click behavior on a link element.



$( "a" ).click(function( event ) {





Notice that we passed the event to the customized function. This event can then be used to call methods associated with it. In this example, we call the preventDefault method. This method stops the default action, so when the user clicks the link nothing happens. THe user is not redirected to a new location and a new site isn't opened.

The final common event that you'll use in web development is the submit event. This event occurs when the user clicks the submit button for a form. It's common to override the submit event to check if a form is properly filled out before you send the data to the server. You might have other reasons to override the event, but this is the most common. It's common to tie the preventDefault event method with the submit event to prevent a form from submitting if the user doesn't fill out all necessary text boxes.

The following jQuery code overrides the submit event and checks for a value in the "firstname" form text box.



$( "form" ).submit(function( event ) {

 if ( $( "#firstname" ).val() == "" ) {

    $( "span" ).text( "Please enter a value." );








In the above code, when the user clicks the form submit button, the event is captured and the "firstname" form is evaluated. If it's left blank with no value, then the text "Please enter a value" is shown in the span element. The return statement returns the function without completing the submission event. The preventDefault method is called, which stops the form from submitting.

Event Object

In the previous section, we passed the event object to the custom function and used it to call the preventDefault method. You can do the same with other events and use the object to call other events. You can also use it to trigger events.

As we said, events are triggered from user actions, but sometimes you need to trigger these events in your code. You can do this using the event object.

Take a look at the following code.


var e = jQuery.Event( "click" );

 jQuery( "body" ).trigger( e );


In the above code, the click event is assigned to the "e" variable. The event is then linked to the body tag. Remember that the body tag encompasses all the content that the user sees, so the event is triggered with each click in the web page.

You can also target a specific property for an event. Let's say you want to trigger an event based on the key a user presses on the keyboard. You can assign an event to a specific key and link it to the HTML body. The following code links an event to the keycode 64.


var e = jQuery.Event( "keydown", { keyCode: 64 } );

jQuery( "body" ).trigger( e );


In the above code, notice that we specify the event and then the event property we want to link. This means that not all key presses will trigger the event. Only the key that matches the keycode 64 will trigger the event.

Using Delegates

You can set a delegate for an event and either call a function or create your own custom code. The "delegate" method let's you set a delegate function to handle an event within a specific element. For instance, you might want to override the standard event function when a user clicks a table row. Normally, nothing happens when the row is clicked, but you can override this behavior and set your own custom function.

The standard format for setting a delegate is as follows:


$( elements ).on( events, selector, data, handler );


The events are a list of actions that you want to override. The selector tells the function what elements to use. The data parameter is the data to pass, and the handler is the custom function that handles the event. You define this function in your jQuery code.

Take a look at the following code that uses a delegate function.


$( "table" ).delegate( "tr", "click", function() {

 $( this ).toggleClass( "loadrecord" );



In the above code, we override the click event on a table row (tr). When the user clicks a table row, the delegate toggles the class to "loadrecord." This class could change the way the table row is displayed to the user. What happens in this class is up to you.

Using events is common in the jQuery framework. It's one of the most common reasons to use jQuery over JavaScript, because it makes overriding default behavior much easier. Using events is the foundation of jQuery and client-side code that dynamically manipulates the elements that make your frontend web design. With event's, you can completely override standard functionality and create a web page that sends output based on your user input.

Popular Courses
Learn More! Take an Online Course...
Follow Us Online
  • Follow us on Google Plus Follow us on FaceBook Follow us on Twitter Follow us on YouTube
© Copyright 1999-2019 Universal Class™ All rights reserved.