How to stop default link click behavior with jQuery

smartcaveman picture smartcaveman · Apr 12, 2011 · Viewed 139.2k times · Source

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?

Answer

Upvote picture Upvote · Apr 12, 2011
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.