Different Types of Event Handling in jQuery
 
 

Different Types of  Event Handling in jQuery

Your browser handles events such as clicks, double-clicks and mouse over actions. The jQuery framework lets you override these defaults and specify an alternative for an event. This alternative is called an event handler. In some rare cases, you need to trigger an event in your code. However, if you don't have a handler specified in jQuery, the browser default handler is used. In this article, we'll discuss triggering events, deregistering events and even creating your own.

Triggering Events

Before you trigger events, you have to understand the way they are handled in a browser. As you know, jQuery and JavaScript code are completely optional in a web page. When a user clicks a button, you don't need jQuery to handle the output. The browser has its own handlers to work with a button.

The jQuery framework has the "trigger" method that lets you trigger an event handler. If you haven't overridden the handler with your own function, then this method does nothing to change the current page behavior. However, the "simulate" method can emulate a user click and trigger default browser behavior. In this section, we'll take a look at both of these methods.

Take the following HTML link as an example.

<a href="mypage.com">Click here to open my page</a>

The default click action is handled by your browser. You don't need to write a jQuery function to handle what happens when the user clicks the link. The browser sends the user to the "mypage.com" website when the link is clicked. What if you want to automatically click the link for the user? It's not a common website design, but there are times when you need to trigger user action. The following jQuery code triggers the click event.

$( "a" ).trigger( "click" );

We never defined a jQuery event handler for this event, so nothing about the page changes.

The "simulate" method can emulate a user click, which triggers the browser's default behavior. The following jQuery code uses the simulate method instead.

$( "a" ).simulate( "click" );

In the above code, whatever default behavior the browser has for the specific element is used instead. If you use this method, remember that each browser can have different behavior depending on several factors including version and operating system. If there is any question about the way a default handler works, it's best to create your own event handler.

Let's say we create our own event handler for a form text box.

var btnclick = function ( event ) {

            console.log ("The event was triggered.");

};

In the above code, we create a custom function and then assign it to a variable. You can use this variable to assign the custom function to an event such as a click. You can trigger this event two ways in your jQuery code. The first one is by using the trigger method. The following code uses this method to simulate the click event.

$( "a" ).on( "click", btnclick );

$( "a" ).trigger( "click" );

The first line of code connects the new btnclick function with the click event on a link. This line of code does not actually perform the click. It just links the event to the function. It's the second line of code that actually triggers the event. This trigger will run the btnclick event.

Even though the code is technically correct, most programmers agree that it's not efficient. Instead of triggering an event, you should just call the function. The following code accomplishes the same procedure as the previous snippet.

$( "a" ).on( "click", btnclick );

btnclick();

The above code still links the btnclick function with the click event, so when users click the link the btnclick function runs. However, then it runs the btnclick function directly instead of triggering an event. This type of syntax is preferred for performance and efficiency.

You have one other way to trigger just the event handler and not the actual default browser behavior. The "triggerHandler" method invokes the method linked to a specific handler but does not trigger the default action.

The important distinction between the triggerHandler and trigger methods is that trigger sends the browser a command to emulate a user click. The click is emulated and the handler is triggered. The triggerHandler method only invokes the function defined for the event.

The following code shows you the difference.

<button>This button will lose and gain focus</button>

<p></p>

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

$( "button" ).focus(function() {

 $( "p" ).text("The button was clicked");

});

$( "button" ).trigger( "focus" );

$( "button" ).triggerHandler( "focus" );

In the code above, we have a button that we'll use to illustrate the difference between the two methods. We create a "focus" function. This function just writes text to the paragraph. When the trigger method executes, it gives focus to the button and then adds text to the paragraph. The focus action happens because the focus event gives an element focus. The next statement uses the triggerHandler method. When this method is triggered, the button does not receive focus. However, the text in the paragraph is still added and shown in the browser.

Deregistering Events

The jQuery framework has two ways to bind an event handler to an event. We saw the "on" method in the previous section. This is the preferred way to bind handlers. Older versions of jQuery also use the "bind" method to link an event with a handler. Once you bind an event handler to a function, each time the user triggers it through the browser the function runs.

Even though you usually want to keep a handler bound to an element, there are times that you want to remove the handler from the binding. You might want to return the element to its default state, or you might want to remove the handler dynamically to then create a new function that runs after some user input. The handler can be removed using a button or just programmatically in your code.

The following jQuery code removes a binding after the user clicks a button.

$( "button" ).click(function() {

 $( "#secondbutton" )

    .unbind( "click", clickfunction )

});

In the code above, when a user clicks a button, the "unbind" method is called on a button with the ID "secondbutton." The unbind method removes a custom handler, which in this example is named "clickfunction." Even though the custom handler is removed from the button's bindings, doesn't mean that the button no longer functions. When you remove a handler's bindings in jQuery, no longer handles any events such as the click event. Instead, handling is returned to the browser.

You can choose to turn off all handlers for an element. Remember that you can have a handler assigned to multiple elements, or you can assign each element its own handler. In some cases, you might want to remove all handlers across the board for all elements with a specific tag. If you use the code above, you might want to unbind a paragraph element from all bound functions.

The "off" method removes handlers from your elements. The following jQuery code removes all handlers from a button element.

$( "button" ).off();

That's all it takes to remove all handlers. You can also use this method to remove handlers from other elements such as those that match a specific class or even just one element with a specific ID. Note that all handlers are removed, so it is a global removal that you might now want to do. You can remove specific handlers from an element instead of all of them using the following code.

$( "p" ).off( "click", "**" );

This statement removes all delegate click handlers from paragraph tags. Notice that it only removes click handlers and not any other handlers if you have them for your paragraph.

You can also remove specific handlers for specific elements. This will only remove the custom function with the given name. This leaves all other handlers bound to the element.

The following code removes only the "clickfunction" handler from the button element.

$( "body" ).off( "click", "button", clickfunction );

The above code makes the "off" method much more granular, so you can be more specific on the functions and handlers that you want to deactivate. The first parameter specifies the event that you want to deactivate. The second parameter is the element that you want to work with, and the clickfunction is the name of the event handler that you want to remove from the element.

You can still link a new event handler to the element using the "on" method. The following method links a new event handler to the button's click event.

$( "body" ).on( "click", "button", newclickfunction );

If you decide to rebind a function to an event, the "on" method will relink it to your element. In this example, the "on" method is used to link the click method to the button element. The new function that's linked to the handler is "newclickfunction." You can also link the original handler to the event. You can turn event handler linking on and off dynamically with jQuery.

Your Own Events

When you override events, you use your own functions to define the way a handler works. It's important to understand that your functions completely override the behavior of an element when it's clicked or any other interaction your user has with it.

You can write your own events with any element in the DOM. You just need to link the event handler with the element. Remember that you can link any function with any element in the DOM. You just need to link it and define it. In this section, we'll show you how to define a custom event handler.

Let's first define a custom HTML dropdown box that has several options for the user to choose from. The following HTML code defines a "colors" dropdown element.

<div class="initial" id="colors">

    <div class="red">Red</div>

    <div class="blue">Blue</div>

    <div class="purple">Purple</div>

    <div class="orange">Orange</div>

</div>

Suppose you want to highlight each div container when the user clicked an option... You want to change the background of the Red container to red when it's selected, blue when the Blue container is selected, purple when the Purple container is selected, and orange when the Orange container is selected. You can set this type of procedure with your own custom event handlers.

Take a look at the following jQuery code.

$( ".red" ).on( "red:toggle", function( event ) {

    var red = $( this );

    if ( red.is( ".on" ) ) {

        red.removeClass( "on" ).addClass( "off" );

    } else {

        red.removeClass( "off" ).addClass( "on" );

    }

});

In the above code, we create our own "toggle" function that defines the way an event is handled when a user clicks the "red" option. It's common to work with toggling events when the user continues to click an element. Each time the user clicks an option, the "toggle" event changes the option from one to the other.

In this example, the "red" option is changed to "on" and "off." The method used is "addClass." The addClass method adds a CSS class to an element. If you add or remove this class, you can change the visual output as the user continues to click the element. In this case, the user continues to click the div container. Each time the user clicks the same container, the class is toggled on and off. This type of custom function event handler is one of the main advantages of jQuery and what you can do to create custom event handlers that work with your frontend design.

As we showed you in the previous section, you can bind this custom event handler with your elements and then you can turn it off. The jQuery framework's advantage is turning these handlers on and off depending on your user's input.

With the event handler defined, you can then turn it on and off. You can also trigger an event using the trigger method. Remember that you can also trigger just the function without the event using the triggerHandler method.

If you want to trigger just the handler, you use the triggerHandler event. If you want to trigger the handler that invokes the custom handler as well as the action in the browser, you use the trigger method.

The following code shows you how to invoke both.

$( "button" ).trigger( "click" );

$( "button" ).triggerHandler( "clickfunction" );

In the first statement, the trigger method invokes the action when the user clicks the button. It emulates the same action and function when the user clicks a button. In the second statement, the triggerHandler method just invokes the method that runs when the user triggers an event. Remember to always use this distinction when you create new events and use jQuery methods to invoke different actions.