JavaScript JavaScript and the DOM 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
185,909 Points

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

3 Answers

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';  
});
}
Steven Parker
Steven Parker
185,909 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.