I have a div container, where for some reason I have to add e.preventDefault()
, but surprisingly it stops the anchor elements to do their job as well
jQuery('#anything').on("click", function(e) {
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="anything">
<a href="https://google.com"> Link should work </a>
</div>
I didn't expect that anchor won't work, I never had to deal with this before. I tried StopPropagation()
as suggested somewhere, But that didn't work
How can I make the anchor working again?
One option would be to use event delegation and exclude all a
s from triggering the listener:
jQuery('#anything').on("click", '*:not(a)', function(e) {
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="anything">
<a href="https://google.com"> Link should work </a>
</div>
Or if you want to make sure that no clicks inside children of #anything
trigger the listener, put #anything
as the delegation selector instead. In native Javascript this time:
document.querySelector('#anything').addEventListener('click', (e) => {
console.log('listener running');
if (!e.target.matches('#anything')) return;
console.log('prevented default');
e.preventDefault();
});
<a href="www.google.com" id="anything">Parent A<span>Child Span</span></a>
(though, preventDefault()
on just a div
doesn't much sense..?)
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