Brandon Contreras Brandon Contreras - 2 months ago 18
Javascript Question

Scope of event Listeners inside loop

How is the eventListener working inside forLoop?

The code works in the example.

When I toggle on either paragraph it turns a lower opacity and has a strike through.
When I hover on either paragraph they turn blue.

I want to understand how this is achieved inside a for loop after the browser loads the page. I'm just trying to understand how the browser interprets this code.



var someTag = document.querySelectorAll("p")

for (var i = 0; i < someTag.length; i++) {


someTag[i].addEventListener('mouseover', function() {
this.classList.add("someClass");
});
someTag[i].addEventListener('mouseout', function() {
this.classList.remove("someClass");
});

someTag[i].addEventListener('click', function() {
this.classList.toggle("done");
})


}

.done {
text-decoration: line-through;
opacity: 0.5;
}

.someClass {
color: blue;
}

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>




Answer

When you add an event listener to an element, that's a permanent change to that element (unless you later remove it with removeEventListener()). The listener function will be called automatically by the browser whenever the event is triggered on the element. You only need to add the listener once, it will then react to all future occurrences of the event.

The other thing you need to know is that within the listener function, this will be a reference to the element that the event was triggered on. That's how your functions are able to change the class of the paragraph you click or hover on.