Theodore Steiner Theodore Steiner - 7 months ago 20
Javascript Question

Checking Clicked Element in Bubbling

I was tinkering with event bubbling and I created the typical 3 divs each other exercise for myself and I was able to get the code working and event to stop "bubbling" where I wanted.

My code was clunky so I tried to make it a little more simplified. By having all my

<divs>
point to a single function, that had a statement that said if this
<div>
was clicked, run the function and then stop propagation, but I believe the way I am "checking" the click is wrong.

Link: https://jsfiddle.net/theodore_steiner/t5r5kov0/3/



var d1 = document.getElementById("d1");
var d2 = document.getElementById("d2");
var d3 = document.getElementById("d3");

function showme(event) {
if (d3.onclick == true) {
alert("hello")
event.stopPropagation();
} else {
alert("hello");
}
};

d1.addEventListener("click", showme);
d2.addEventListener("click", showme);
d3.addEventListener("click", showme);

#d1 {
height: 300px;
width: 300px;
border: 1px solid black;
}
#d2 {
height: 200px;
width: 200px;
border: 1px solid black;
}
#d3 {
height: 100px;
width: 100px;
border: 1px solid black;
}

<div id="d1">
<div id="d2">
<div id="d3">
</div>
</div>
</div>




Answer

Use event.target.id as event.target will return element on which event is invoked and id is a property of the DOMElement

Event.target, A reference to the object that dispatched the event.

var d1 = document.getElementById("d1");
var d2 = document.getElementById("d2");
var d3 = document.getElementById("d3");

function showme(event) {
  if (event.target.id == 'd3') {
    alert("hello")
    event.stopPropagation();
  } else {
    alert("hello");
  }
};

d1.addEventListener("click", showme);
d2.addEventListener("click", showme);
d3.addEventListener("click", showme);
#d1 {
  height: 300px;
  width: 300px;
  border: 1px solid black;
}
#d2 {
  height: 200px;
  width: 200px;
  border: 1px solid black;
}
#d3 {
  height: 100px;
  width: 100px;
  border: 1px solid black;
}
<div id="d1">
  <div id="d2">
    <div id="d3">
    </div>
  </div>
</div>

Comments