How to stop default link click behavior with jQuery

JavascriptJqueryEventsClickJquery Events

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

$('.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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

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);	

Solution 6 - Javascript

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?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsmartcavemanView Question on Stackoverflow
Solution 1 - JavascriptUpCatView Answer on Stackoverflow
Solution 2 - JavascriptPeeterView Answer on Stackoverflow
Solution 3 - JavascriptJonathon BolsterView Answer on Stackoverflow
Solution 4 - JavascriptNull PointerView Answer on Stackoverflow
Solution 5 - JavascriptMatoeilView Answer on Stackoverflow
Solution 6 - JavascriptAndy BrownView Answer on Stackoverflow