Change the style of an element nodelist on click event

Viewed 2131

I have a problem adding an eventlistener to a nodelist on this website that I'm playing with.

I would like that the elements with class card-img-overlay to change their style on mouseover.

So the first thing i've tried is adding a for loop, like this:

var banner = document.getElementsByClassName("card-img-overlay");

// add a for loop for event listeners on the nodelist
for ( i = 0; i < banner.length; i++) {
    banner[i].addEventListener("click",function(){
 banner[i].style.backgroundColor = "black"});
};

And I get the following error :

VM95:3 Uncaught TypeError: Cannot read property 'style' of undefined at HTMLDivElement. (:3:12)

How can I add an eventListener to a nodelist in a better way? I didnt learn jQuery yet so i prefer to stick on VanillaJS.

Thank you very much!

1 Answers

When the click event fires it doesn't know what i is anymore. You can reference the clicked element with this.

var banner = document.getElementsByClassName("card-img-overlay");

// add a for loop for event listeners on the nodelist
for ( i = 0; i < banner.length; i++) {
    banner[i].addEventListener("click",function() {
        // function will never know what 'i' is here
        this.style.backgroundColor = "black"
    });
};

Fiddle: https://jsfiddle.net/kcr7gLx1/2/

Related