Welcome to the Treehouse Community
Looking to learn something new?
Shane Unger9,413 Points
For loop question
This is going to be difficult to ask, but I'll try my best. What exactly is happening here with the for loop? I understand that it is iterating across the collection of list items, and I am familiar with the general concept of array iteration, but I'm confused in this instance.
So we have a collection of zero-indexed html elements, the list items, and we're iterating over them in order to register the event handlers behavior. I move my mouse over the element at , which is plums i think, and it gets converted to uppercase on mouseover, and lowercase on mouseout. But how is iteration helping with this? Can someone walk me through step by step? The i variable starts at zero, then the conditional statement is true, and the code block executes, but since it starts at zero how does my mousemove over  immediately activate? Is the for loop constantly iterating at a million miles an hour over the whole list, and it's happening so fast that when I mouseover the last one it just so happens to catch it?
Thanks for your help!
The iteration's only purpose is to add the event listener to the elements, that is all it does and it only runs once. The iteration is not responsible for highlighting the element when you mouse over the it.
When you highlight the element that triggers a mouseover event, and since you have added an event listener for that event to the element the code you specified will be triggered. But that has nothing to do with the loop, this project would work fine without a loop but then you would have to write the addEvent code multiple times since you would need to type it for each of the items. The loop is just used to cut down on repeated code.
That is also why the bug demonstrated at the end occurs, where removing an element from the list and adding a new one in breaks the highlighting for the new element. Since the for loop only runs once when the page loads the newly added element has no event listener attached to it.
Daniel Fitzhugh9,715 Points
I opened all the questions to see if this question had been answered, and it has - great :)
And also the fact that the "for loop" is responsible for the new "<li>" not having the eventListener - very useful.