I have a set of div elements inside <a>
tag with it's href.
The question is that there is a div inside of it with its own click event and I want that in case the div element trigger the click event, the <a>
tag should not be triggered.
The function that manage the div click event try to stop propagation with no success.
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
What's wrong?
The answer is the same whether or not you're using jQuery (or most other libraries).
When a link contains another element whose click event shouldn't cause navigation, then simply call preventDefault on the event. There is no jQuery magic here, it's just using a default DOM method:
event.preventDefault();
An example:
function foo(event) {
console.log(event.target.textContent);
if (event.stopPropagation) {
// Stop propagation
event.stopPropagation();
// Stop default action
event.preventDefault();
}
// IE model
event.cancelBubble = true;
event.returnValue = false;
return false;
}
// Attach the listeners
document.getElementById('d0').addEventListener('click', foo, false);
document.getElementById('d1').addEventListener('click', foo, false);
Click on the Div, no click reaches the A element
<a href="#" onclick="console.log('Click reached ' + this.textContent)">Link
<div id="d0">Div</div>
</a>Click on the Div, the link isn't followed
<a href="http://www.apple.com">Apple
<div id="d1">Div</div>
</a>
The trick is that a click on the div
doesn't bubble to the link, but without preventDefault
, link is followed anyway.
A better idea is to not to do this at all. The div
doesn't appear to belong to the A element, so put it outside. Then there are no issues with a click on the div
causing navigation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With