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 trialRoudy Antenor
4,124 PointsHow 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
3 Answers
Steven Parker
231,248 PointsThe "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
7,793 PointsThanks 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
4,124 Pointsonst 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';
});
}
james south
Front End Web Development Techdegree Graduate 33,271 Pointscan you post some sweet sweet markdown-formatted code?
Steven Parker
231,248 PointsSteven Parker
231,248 PointsTo make an analysis possible, please show your code (remember to format it with Markdown).