Jake Jake - 3 months ago 10
Javascript Question

Variable Undefined in Click Event Listener

The Variable slide_titles and slide_background are logging out as undefined in the Click Event Listener. Why is this?

Im trying to add and remove classes using classList. It's not working because the global variables aren't visible inside the on click EventListener.

html

<div class="product-type">
<ul>
<li class="slide__title selected">Cars</li>
<li class="slide__title" >Motorcycles</li>
<li class="slide__title">Power Equiptment</li>
<li class="slide__title">Marine</li>
</ul>
</div>

<ul id="slides">
<li class="slide cars"></li>
<li class="slide bikes"></li>
<li class="slide mower"></li>
<li class="slide boat"></li>
</ul>


javascript

var slide_titles = document.querySelectorAll('.slide__title');
var slide_background = document.querySelectorAll('.slide');


function removeSelected() {
for(var i = 0; i < slide_titles.length; i++) {
if(slide_titles[i].className.indexOf('selected') != -1) {
console.log("remove");
slide_titles[i].classList.remove("selected");
}
}
}


var clickEvent = function(index) {
slide_titles[i].addEventListener("click", () => {
removeSelected();
slide_background[i].classList.add("show");
slide_titles[i].classList.add("selected");
console.log(slide_background[i]);

});
}


for(var i = 0; i < slide_titles.length; i++) {
clickEvent(i);
}


here is the fiddle https://jsfiddle.net/6yjfdftc/1/

Answer

It's logging undefined because i is undefined in that scope. Since you pass i to it in your for loop, try this:

var clickEvent = function(index) {
    slide_titles[index].addEventListener("click", () => {
        removeSelected();
        slide_background[index].classList.add("show");
        slide_titles[index].classList.add("selected");
        console.log(slide_background[index]);
    });
}

Here's an updated fiddle.

Comments