Reputation: 1615
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>
Upvotes: 0
Views: 607
Reputation: 36609
Use
event.target.id
asevent.target
will returnelement
on whichevent
isinvoked
andid
is a property of theDOMElement
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>
Upvotes: 2