JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

Enes AKGÜN
Enes AKGÜN
1,549 Points

The program does not work with 'for loop'.

The program works without the for loop ( first list element), but as soon as I put listeners in for loop hovering doesn't work anymore and I don't get any errors.

for (let i=0; i<listItems.length; i+=1){ listItems[i].addEventListener("mouseover", () => { listItems[i].textContent =listItems[i].innerHTML.toUpperCase(); });

listItems.addEventListener('mouseout', () => { listItems[i].textContent=listItems[i].textContent.toLowerCase(); });

}

1 Answer

Stephan Olsen
Stephan Olsen
6,648 Points

I formatted your code. When you're adding your second eventListener, you omitted the [i], which is why it doesn't work.

for (let i=0; i<listItems.length; i+=1) { 
    listItems[i].addEventListener("mouseover", () => { 
    listItems[i].textContent =listItems[i].innerHTML.toUpperCase(); 
    });

    // Missing [i] here.
    listItems.addEventListener('mouseout', () => { 
    listItems[i].textContent=listItems[i].textContent.toLowerCase(); 
    });
}