Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .live('click') vs .click()

Tags:

jquery

live

I am wondering whether there are any circumstances where it would be better to use .click(function {...}); rather than .live('click', function {...});?

From what I gather the live option seems to be a better option and I am hence using it in almost all circumstances instead of the plain .click(), especially given a lot of my code is loaded asynchronously.

EDIT: Another part to this question. If I'm asynchoronously loading all the javascript in, .click will still pickup all elements already in the dom. Right?

like image 352
kalpaitch Avatar asked Feb 09 '11 11:02

kalpaitch


People also ask

What is the difference between on click 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. When .

What is difference between .click and .onclick function?

In click() it will be the object on which the handler is attached. In onclick() it would be a normal function call and this would be inherited from the calling context.

What is the use of live in jQuery?

The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur. Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).

What is Click () method?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.


1 Answers

There might be times when you explicitly want to only assign the click handler to objects which already exist, and handle new objects differently. But more commonly, live doesn't always work. It doesn't work with chained jQuery statements such as:

$(this).children().live('click',doSomething); 

It needs a selector to work properly because of the way events bubble up the DOM tree.

Edit: Someone just upvoted this, so obviously people are still looking at it. I should point out that live and bind are both deprecated. You can perform both with .on(), which IMO is a much clearer syntax. To replace bind:

$(selector).on('click', function () {     ... }); 

and to replace live:

$(document).on('click', selector, function () {     ... }); 

Instead of using $(document), you can use any jQuery object which contains all the elements you're monitoring the clicks on, but the corresponding element must exist when you call it.

like image 172
Nathan MacInnes Avatar answered Oct 03 '22 12:10

Nathan MacInnes