javascript - Variable Undefined in Click Event Listener -


the variable slide_titles , slide_background logging out undefined in click event listener. why this?

im trying add , remove classes using classlist. it's not working because global variables aren't visible inside 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 = 0; < 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 = 0; < slide_titles.length; i++) {       clickevent(i);    } 

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

it's logging undefined because i undefined in scope. since pass i in 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 updated fiddle.


Comments