Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery changing .live to .on,

Tags:

jquery

I am trying to change all my .live() to .on() as the prior is now deprecated.

I am struggling to understand how it works though. Before I used this code and it worked fine...

$('#lightBoxClose').live('click', function() {
    $('#lightBox').fadeOut();
});

So I tried changing it to,

$('#lightBoxClose').on('click', function() {
    $('#lightBox').fadeOut();
});

But it doesn't work can anyone please explain what I am supposed to be doing thanks.

like image 762
cgwebprojects Avatar asked Mar 29 '12 22:03

cgwebprojects


People also ask

What is .live in jQuery?

jQuery | live() MethodThis method is used to attach one or more event handlers for the selected elements. It also specifies the function that runs when the event occurs. The event handlers used will work for both current and future elements matching the selector.

What is difference between BIND and live in jQuery?

In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future.

What is the difference between on and live in jQuery?

on() method: This method attaches events not only to existing elements but also for the ones appended in the future as well. The difference here between on() and live() function is that on() method is still supported and uses a different syntax pattern, unlike the above two methods.


1 Answers

You have to bind to an element that already exists at the time of the binding, passing the target selector as the second argument. That element must be an ancestor of the eventual click target, so it can catch the bubbled event. This technique is called delegation.

For example, using the document element:

$(document).on('click', '#lightBoxClose', function() {
    $('#lightBox').fadeOut();
});
like image 110
bfavaretto Avatar answered Oct 15 '22 11:10

bfavaretto