91

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?

Patrick
  • 483
  • 1
  • 5
  • 18
smartcaveman
  • 38,142
  • 26
  • 119
  • 203
  • possible duplicate of [jQuery disable a link](http://stackoverflow.com/questions/970388/jquery-disable-a-link) – user Mar 02 '14 at 05:21

6 Answers6

139
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.

sepans
  • 1,332
  • 13
  • 24
Upvote
  • 65,847
  • 122
  • 353
  • 577
36
$('.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.

Peeter
  • 8,952
  • 4
  • 34
  • 52
  • Why do I need to call `stopPropagation()` and `preventDefault()`? – smartcaveman Apr 12 '11 at 09:11
  • 2
    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. – Peeter Apr 12 '11 at 09:13
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.

Jonathon Bolster
  • 15,221
  • 3
  • 39
  • 46
3

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

Null Pointer
  • 8,509
  • 25
  • 68
  • 115
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);  
Matoeil
  • 5,944
  • 9
  • 47
  • 69
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?

Andy Brown
  • 4,841
  • 3
  • 29
  • 35