Patrick Desjardins Blog
Patrick Desjardins picture from a conference

JQuery .on() function

Posted on: 2012-06-17

JQuery provide good examples concerning adding event to an Html Dom object dynamically. This mean that event if the Dom doesn't exist, when the event is attached, that the event will be hooked when the Html Dom object. The methodology of this thinking has changed since Jquery version 1.3. At first, we had to use the live method.

$("a.offsite").live("click", function(){ alert("Goodbye!"); }); // jQuery 1.3+ 

In the version 1.4.3, we could have used the delegate function.

$(document).delegate("a.offsite", "click", function(){ alert("Goodbye!"); }); // jQuery 1.4.3+ 

But now, to reduce the confusion between all the function to attach event (bind(), live(), delegate()) to Html Dom object, we simply use the ON function.

$(document).on("click", "a.offsite", function(){ alert("Goodbye!"); }); // jQuery 1.7+ 

In this example, since the .on() function is called from the $(document) this will listen every html that change to hook the function if the selector match.

The syntax of the on function in Jquery is :

.on( events [, selector] [, data], handler(eventObject) ) or .on( events-map [, selector] [, data] ) 

This mean that you first select the event you want to add, then the selector in the Jquery syntax and finallywhat you want to hook to.

But you are not limited to listen every thing on the web page. This is usefull is you load content from Ajax but if you want to add an event only on a specify part of the page you can specify it instead of document and add the event.

$("#myTable tr").on("click", function(event){ alert($(this).text()); }); 

This will add to every line of the myTable the possibility to click. If you want to have new line (Javascript added tr) of this grid to be automatically bound to the click event, you need to change the above code to setup the onclick on the table.

$("#myTable").on("click", "tr", function(event){ alert($(this).text()); }); 

This way, it bubbles up to the myTable, which is always available and the click will occur.

Watch out with attaching from the document. Attaching many delegated event handlers near the top of the document tree can degrade performance rapidly. This is even more true with event like mousemouve that is called a lot of time consequently.