Use mouseenter event instead, which doesn't bubble with children elements like mouseover
does.
In other words with mouseover
the event will be attached to all the element children
too, so when you hover a child the event will be fired as if we left the parent div
.
Demo:
document.getElementById("test").addEventListener("mouseenter", function(event) {
var target = event.target;
console.log(target.id);
}, false);
.child {
min-width: 50px;
min-height: 50px;
padding: 10px;
display: inline-block;
background-color: yellow;
}
.parent {
padding: 20px;
background-color: red;
}
<div id="test" class="parent">
<div id="child1" class="child">1</div>
<div id="child2" class="child">2</div>
<div id="child3" class="child">3</div>
<div id="child4" class="child">4</div>
<div id="child4" class="child">5</div>
</div>
You can see in the above snippet that using mouseenter
the event is always firing even if we hover over children and only the parent id
is logged, as if we didn't leave it.
Mouseover demo:
You can see the difference here using mouseover
event:
document.querySelector(".parent").addEventListener("mouseover", function(event){
console.log(event.target.id);
});
.child {
min-width: 50px;
min-height: 50px;
padding: 10px;
display: inline-block;
background-color: yellow;
}
.parent {
padding: 20px;
background-color: red;
}
<div class="parent">
<div id="child1" class="child">1</div>
<div id="child2" class="child">2</div>
<div id="child3" class="child">3</div>
<div id="child4" class="child">4</div>
<div id="child4" class="child">5</div>
</div>
mouseover
event triggers both for the child as the parent element. – Prenatalmyfunction
return true or false? – Emmons