Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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>
like image 605
dougkramer Avatar asked Jun 19 '10 18:06

dougkramer


People also ask

How do you prevent event propagation?

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

How do you stop event propagation with inline onClick attribute?

Use event. stopPropagation(). This is just wrong - inline onclick handlers don't get the event passed as an argument.

Which event can be used to stop event propagation in react?

14, returning false from an event handler will no longer stop event propagation. Instead, e. stopPropagation() or e. preventDefault() should be triggered manually, as appropriate.


2 Answers

Change your function definition to include the event:

function showMenu(event, element) {
  alert("div clicked");
  // Don't propogate the event to the document
  if (event.stopPropagation) {
      event.stopPropagation();   // W3C model
  } else {
      event.cancelBubble = true; // IE model
  }
}

Then change the call to pass in the event:

div id="fooddmenu" onclick="showMenu(event, this);">Click inside this div</div>
like image 51
Hooray Im Helping Avatar answered Oct 13 '22 18:10

Hooray Im Helping


Try EventListeners:

html:

<div id="fooddmenu">Click inside this div</div>or click outside the div.​​​​​​​​​​

js:

function showMenu(e) {
    alert("div clicked");
}

document.onclick = function() {
    alert('document clicked');
};

window.onload = function(){
    document.getElementById("fooddmenu").addEventListener("click", function(e){
        showMenu(this);
        e.stopPropagation();

    });
};
like image 38
tcooc Avatar answered Oct 13 '22 18:10

tcooc