Search code examples
javascriptvariablesslider

Slider controllers


I'm trying to make an slider with two types of controllers (dots, and slide names). I'm finding troubles trying to make this two controllers react at the same time. When clicking the dot controller number 2 an active class is add to the dot. At the same time the slide name controller number 2 should have that active class. I'm stuck :(enter image description here

var sliderName = document.getElementsByClassName("slider-name");
var sliderDot = document.getElementsByClassName("slider-dot");
for (var i = 0; i < sliderName.length; i++) {
   sliderName[i].addEventListener("click" , function clickBtn() {
      this.classList.toggle("slider-btn-active");
      sliderDot[i].classList.toggle("slider-btn-active");
      /*var test = this.parentElement.previousElementSibling.children[i];
      alert(test);
      this.parentElement.previousElementSibling.children.classList.toggle("slider-btn-active");*/
   });
}

Solution

  • If I'm understanding you correctly, you want the classes to toggle both when clicking the sliderName and the sliderDot?

    You could create a goToSlide function by itself and use it for both clicks on the sliderName and the sliderDot.

    var sliderName = document.getElementsByClassName("slider-name");
    var sliderDot = document.getElementsByClassName("slider-dot");
    
    function goToSlide(slideIndex) {
      sliderName[slideIndex].classList.toggle("slider-btn-active");
      sliderDot[slideIndex].classList.toggle("slider-btn-active");
    }
    
    for (let i = 0; i < sliderName.length; i++) {
      sliderName[i].addEventListener("click" , function () {
         goToSlide(i);
      });
      
      sliderDot[i].addEventListener("click" , function () {
         goToSlide(i);
      });
    }