Frederick M. Rogers Frederick M. Rogers - 1 year ago 68
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

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

The problem I am having is when I use
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
everything works fine. I have googled and youtubed and I can't find a solution. I would appreciate any and all assistance, thank you.


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() {
// = 'red'; = 'none';
function mouseOut() {
// = 'grey';

Codepen example

Answer Source

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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download