Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {     MoneyBox.closeBox();     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 () {     MoneyBox.closeBox();     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 on() instead but either way why use live/on() instead of my first example?

like image 446
JasonDavis Avatar asked Apr 10 '12 01:04

JasonDavis


People also ask

What is difference between on and click in jQuery?

on() differs from . click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas . click() does not.

What can I use instead of click in jQuery?

Why use jQuery on() instead of click()

What is on () in jQuery?

The on() is an inbuilt method in jQuery which is used to attach one or more event handlers for the selected elements and child elements in the DOM tree.

Why click function is not working in jQuery?

The fix is easy enough, simply bind the OnClick event to the parent of the elements you want to be able to click on. That way, if the element you want to click on is removed and re-appended, the handler will still be there listening as the parent was never removed.


1 Answers

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:

http://jsfiddle.net/AJRw3/

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

like image 85
Andreas Wong Avatar answered Oct 13 '22 05:10

Andreas Wong