How to stop default link click behavior with jQuery
Asked Answered
K

6

98

I have a link on a web page. When a user clicks it, a widget on the page should update. However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires.

This is what the link looks like:

<a href="store/cart/" class="update-cart">Update Cart</a>

This is what the jQuery looks like:

$('.update-cart').click(function(e) { 
  e.stopPropagation(); 
  updateCartWidget(); 
});

What is the problem?

Knightly answered 12/4, 2011 at 7:52 Comment(1)
possible duplicate of jQuery disable a linkChemotherapy
B
146
e.preventDefault();

from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

Cancels the event if it is cancelable, without stopping further propagation of the event.

Berte answered 12/4, 2011 at 7:53 Comment(1)
Thanks, I had stopPropagation and preventDefault confusedKnightly
D
37
$('.update-cart').click(function(e) {
    updateCartWidget();
    e.stopPropagation();
    e.preventDefault();
});

$('.update-cart').click(function() {
    updateCartWidget();
    return false;
});

The following methods achieve the exact same thing.

Dependence answered 12/4, 2011 at 8:22 Comment(2)
Why do I need to call stopPropagation() and preventDefault()?Knightly
Look at Jonathons answer, he explains what each function does. But basically, to make sure the click you just handled isn't handled by someone else later.Dependence
S
31

You want e.preventDefault() to prevent the default functionality from occurring.

Or have return false from your method.

preventDefault prevents the default functionality and stopPropagation prevents the event from bubbling up to container elements.

Shul answered 12/4, 2011 at 7:54 Comment(0)
G
4

You can use e.preventDefault(); instead of e.stopPropagation();

Gwyn answered 8/10, 2011 at 5:37 Comment(0)
D
1

This code strip all event listeners

var old_element=document.getElementsByClassName(".update-cart");    
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);  
Dishevel answered 13/1, 2016 at 10:39 Comment(0)
T
0

I've just wasted an hour on this. I tried everything - it turned out (and I can hardly believe this) that giving my cancel button and element id of cancel meant that any attempt to prevent event propagation would fail! I guess an HTML page must treat this as someone pressing ESC?

Testimonial answered 25/2, 2021 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.