Quantcast
Channel: How to stop onclick event in div from propagating to the document? - Stack Overflow
Viewing all articles
Browse latest Browse all 8

How to stop onclick event in div from propagating to the document?

$
0
0

I want to stop propagation of this div's onclick event to the document? When the user click on the "div", both alerts appear: 1) the div's alert and 2) the document's alert. I want to suppress the document alert.

I know how to do it using addEventListener, but is there another way to to do it? The problem below is that I don't know how to get ahold of the event -- I tried "event = element.onclick", shown below, but that doesn't work. How do I get the event?

<head><script>  function showMenu(element) {      alert("div clicked");      event = element.onclick;  // HOW TO GET HOLD OF THE EVENT?      // Don't propogate the event to the document      if (event.stopPropagation) {          event.stopPropagation();   // W3C model      } else {          event.cancelBubble = true; // IE model      }  }  document.onclick = function() {      alert('document clicked');  };</script></head><body><div id="foodmenu" onclick="showMenu(this);">Click inside this div</div>  or click outside the div.</body>

Viewing all articles
Browse latest Browse all 8

Latest Images

Trending Articles





Latest Images