Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) 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,650 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(); 
    });
}