Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent default event firing but still allow event to bubble

Using jQuery: with the following code I'd like to prevent the href url (in this case a hash '#') being fired on click, but still allow the click event to continue bubbling up the chain. How can this be achieved please?

<div>
    <a href="#">Test</a>
</div>

$('a').click(function(e){
    // stop a.click firing but allow click event to continue bubbling?
});
like image 982
Steve Avatar asked Jul 19 '11 10:07

Steve


People also ask

Does prevent default stop bubbling?

preventDefault() Prevents the browsers default behaviour (such as opening a link), but does not stop the event from bubbling up the DOM.

How would you stop the default action of an event?

To prevent the default action of an event, you can call the Event. preventDefault() method. This method cancels the event if it is cancelable: Event.

Which method prevent the event from bubbling up the DOM tree?

stopPropagation()Returns: undefined. Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Which of the following options is used to prevent default behavior of an event?

preventDefault() will prevent the default event from occuring, e.


1 Answers

$('a').click(function(e){
    e.preventDefault();
    // stop a.click firing but allow click event to continue bubbling?
});

e.preventDefault() won't prevent bubbling, e.stopPropagation() or return false (stop both) will.

like image 176
Shef Avatar answered Oct 09 '22 15:10

Shef