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()

Roudy Antenor
Roudy Antenor
4,124 Points

How does the for-loop get triggered enclosing both event listeners?

My code works - but i am confused as to how the for loop is being triggered when it surrounds the actual event listeners -- and is not part of the function parameter that makes up the addEventListener . Shouldn't it be part of the functions inside the eventlistener call?

To clarify - The mouseover event triggers the function that follows it - how then is the for loop being triggered if the addEventListener sits inside of it ? Thanks in advance

Steven Parker
Steven Parker
229,732 Points

To make an analysis possible, please show your code (remember to format it with Markdown).

3 Answers

Steven Parker
Steven Parker
229,732 Points

The "for" loop is not triggered by any events.

The loop runs only one time, when the page is first loaded. As it runs, it establishes 2 event listeners on each of the list items on the page. Then the loop's job is done.

After that, the event handlers respond to the mouse events, and run the functions that change the background colors.

Devon Stanton
Devon Stanton
7,793 Points

Thanks for the answer, just to clarify.

The page loads and runs the loop and assigns the listeners & the elements to the listItems variable. This is all stored in Memory so when the mouse over happens it pulls the event listener from memory not from the js file? This would explain why the remove and add item function doesn't work anymore because the new item hasn't been stored in the listItems array.

Roudy Antenor
Roudy Antenor
4,124 Points
onst listItems = document.getElementsByTagName('li');


for (let i = 0 ;i < listItems.length ;i++) {
  listItems[i].addEventListener('mouseover', () => {
  listItems[i].textContent = listItems[i].textContent.toUpperCase();        listItems[i] = listItems[i].style.backgroundColor = '#eee';
});
  listItems[i].addEventListener('mouseout', () => {
  listItems[i].textContent = listItems[i].textContent.toLowerCase();        listItems[i] = listItems[i].style.backgroundColor = 'transparent';  
});
}