Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.preventDefault(); not working with .on in jQuery

Tags:

jquery

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?

like image 693
John Avatar asked Jan 17 '23 10:01

John


2 Answers

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/

like image 110
Andreas Eriksson Avatar answered Jan 30 '23 00:01

Andreas Eriksson


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.

like image 26
Rory McCrossan Avatar answered Jan 29 '23 23:01

Rory McCrossan