Handling Events

Events and event handling are an important part of client-side development. Frequently we are tasked with changing their behaviour and part of that process involves locating which methods handle which events. From jQuery version 1.7 onwards, the preferred method of attaching an event handler is .on() http://api.jquery.com/on/ , and its companion methods .on() and .off(). The .on() is a very flexible method because it covers all the capabilities of .live() and .bind() in a single method. By using .on(), the container dom element within which the handler catches events is significantly narrowed down. This improves the efficiency of handling events and makes .on() suitable for handling the higher rates of events that many JavaScript dominated web applications now use. So .on() is both considerably more efficient than .live() , while also being more flexible than .bind() because it handles dynamic groups of dom elements within the selected container. The .live() method is deprecated in version jQuery 1.7 and has now been removed in jQuery 1.9 , so when coding or maintaining any jQuery now, using the .on() method is a move that will save developers maintenance grief in the future.

The following is an example of .on() can attach an event handler directly to a dom element:

$('my_button').on('click',function(){ // action goes here!! });

This is the equivalent of either of:

$('my_button').bind('click',function(){ // action goes here!! });


$('my_button').click(function(){ // action goes here!! });

The Event Object

jQuery hides implementation differences among browsers by defining its own Event object . When a jQuery event handler is invoked, it is always passed a jQuery Event object as its first argument. This object holds additional information about the event. The event object is guaranteed to be passed to the event handler . Most properties from the original event are copied over and normalized to the new event object. It's often helpful to use the extra information contained in the event object passed to the event handler for more control. To become familiar with the event object, use this code to inspect it in your browser console after you click on a < div > in the page.
$( "div" ).on( "click", function( event ) { console.log( "event object:" ); console.dir( event ); });