Q
Q
qwerty12ss2018-10-31 22:45:13
JavaScript
qwerty12ss, 2018-10-31 22:45:13

How to make the slider more flexible?

Good evening. Please tell me if it is possible and how to make the code more flexible. I want that when adding a button and another slider element, I don't have to go into js. I'm interested in the part with addEventListener, I tried to do it through the loop, but it doesn't work, it gives an error.

var slider_btn = document.querySelectorAll(".promo-slider__button");
var slider_item = document.querySelectorAll(".promo-slider__item");
 
var slid = function (number) {
    for (var i = 0; i < slider_btn.length; i++) {
        slider_item[i].classList.remove("promo-slider__item--active");
        slider_btn[i].classList.remove("promo-slider__button--active");
    }
    slider_item[number].classList.add("promo-slider__item--active");
    slider_btn[number].classList.add("promo-slider__button--active");
};
 
slider_btn[0].addEventListener("click", function () {
    slid(0);
});
 
slider_btn[1].addEventListener("click", function () {
    slid(1);
});
 
slider_btn[2].addEventListener("click", function () {
    slid(2);
});
 
slider_btn[3].addEventListener("click", function () {
    slid(3);
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hellcaster, 2018-10-31
@qwerty12ss

for (let i = 0; i < slider_btn.length; i++) {
  slider_btn[i].addEventListener("click", function() {
    slid(i);
  })
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question