Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel bubbling on an HTML anchor tag

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!

like image 987
Navneet Avatar asked Dec 01 '11 00:12

Navneet


2 Answers

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>
like image 184
Poison Oak Avatar answered Oct 01 '22 05:10

Poison Oak


You can return false; or make sure your function is using e as an argument

$("#clickable a").click(function(e){
   //stuff
   e.preventDefault;
});
like image 37
Gregg B Avatar answered Oct 01 '22 05:10

Gregg B