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.
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.
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.
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With