As of jQuery 1.7 .live
has been deprecated and replaced with .on
. However, I am having difficulty getting jQuery .on
to work with event.preventDefault();
. In the below example, clicking the anchor tag takes me to the linked page instead of preventing the default browser action of following the link.
jQuery('.link-container a').on('click', function(event) {
event.preventDefault();
//do something
});
However, the same code with .live
works without any hiccups.
jQuery('.link-container a').live('click', function(event) {
event.preventDefault();
//do something
});
I am using jQuery version 1.7.1 that ships with Wordpress 3.3.1 currently. What have I got wrong here?
You're not binding it correctly. The .on()
-method works like a .delegate()
when doing what you want to do. Here's an example of proper usage:
$('.link-container').on('click', 'a', function(event){
event.preventDefault();
})
This is assuming that .link-container is there on page load, and isn't dynamically loaded. You need to bind the delegate method to the closest ancestor that's statically there, and in the second argument, in this case 'a'
, specify what items the delegate method applies to.
Just using $('selector').on('click', function() { })
gives exactly the same result as using $('selector').click(function(){ })
Here's an example on jsfiddle: http://jsfiddle.net/gTZXp/
If your a
elements are being added dynamically you need to use on()
with a filter (as delegate()
used to be), like this:
jQuery('.link-container').on('click', 'a', function(event) {
event.preventDefault();
//do something
});
This makes the assumption that .link-container
is not dynamic, and is available to the DOM on page load.
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