JasonDavis JasonDavis - 2 years ago 106
jQuery Question

Why use jQuery on() instead of click()

Currently with jQuery when I need to do something when a Click occurs I will do it like this...

$(".close-box").click( function() {
return false;

I was looking at some code someone else has on a project and they do it like this...

$(".close-box").live("click", function () {
return false;

Notice it seems to do the same thing as far as I can tell except they are using the live() function which is now Deprecated and jQuery docs say to use
instead but either way why use live/on() instead of my first example?

Answer Source

Because you might have a dynamically generated elements (for example coming from an AJAX call), you might want to have the same click handler that was previously bound to the same element selector, you then "delegate" the click event using on() with selector argument

To demonstrate:


on() can also be synonymous with click() if you don't have a selector specified:

$('.elementClass').click(function() { // code 

is synonymous with

$('.elementClass').on('click', function() { // code

In the sense that it only add the handler one time to all elements with class elementClass. If you have a new elementClass coming from, for example $('<div class="elementClass" />'), the handler won't be bound on that new element, you need to do:

$('#container').on('click', '.elementClass', function() { // code

Assuming #container is .elementClass's ancestor

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download