Frederick M. Rogers Frederick M. Rogers - 4 days ago 5
Javascript Question

Javascript - mouseover/out event fires on all sibling elements at the same time

I have four sibling elements with a class of "box". I use the

getElementsByClassName()
with a for loop to iterate over the matching set of elements and use the
addEventListener()
method to bind a
mouseover
event to each element.

The problem I am having is when I use
.style.display
in the event handler, and mouse over any of the matching elements, all of the preceding sibling matching elements change their display values.

If I use a different style method like
.style.backgroundColor
everything works fine. I have googled and youtubed and I can't find a solution. I would appreciate any and all assistance, thank you.

Code:

function hover(eClass) {
var elem = document.getElementsByClassName(eClass);
for (var i=0;i<elem.length;i++) {
elem[i].addEventListener('mouseover', mouseOver);
elem[i].addEventListener('mouseout', mouseOut);
}
function mouseOver() {
//this.style.backgroundColor = 'red';
this.style.display = 'none';
}
function mouseOut() {
//this.style.backgroundColor = 'grey';
}
}
hover('box');


Codepen example

Answer

I checked your code. It's fine. In fact, ig you try to hover the last (at the bottom) square, only it will dissapear. When you hower the top one, it dissapears and next one become the top one, so it disappear too, and so on, until all them dissappear. This happen too fast and it seams that all squares dissapear at once...

Comments