I have the following set-up on my webpage
<div id="clickable">
<a href="hello.com">Here!</a>
</div>
Is there a way I could use to avoid the click event for the div to be triggered. I presume it has something to do with setting something in the onclick
attribute for the anchor tag but trying simple things like e.preventDefault()
haven't worked.
Help? Thanks!
Vanilla JS expansion on the accepted answer. event.stopPropagation()
is the most specific and predictable method for preventing events from bubbling to parent containers without disabling the default behavior. In the following examples, the <a/>
will not trigger the alert even though it is contained in a clickable <div/>
.
<script>
function linkHandler(event) {
event.stopPropagation()
}
</script>
<div onclick="alert('fail)">
<a href="http://stackoverflow.com" onclick="linkHandler(event)">Link</a>
</div>
You can return false;
or make sure your function is using e
as an argument
$("#clickable a").click(function(e){
//stuff
e.preventDefault;
});
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