I
I
Ivan Simonov2018-06-06 12:22:04
JavaScript
Ivan Simonov, 2018-06-06 12:22:04

How to fix the code so that two or more sliders work?

Created a simple javascript slider - Fiddle .
But if you add another such slider to html, slider 2 doesn't work - Fiddle .

Alternatively, you can define new classes, and write new code for javascript, but this is most likely the wrong solution.
Tell me what to do in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-06-06
@ivansimonov1984

Add a parameter - the slider's root element selector (or the element itself). Do not search for slides and buttons throughout the document, but inside the root element.

function simpleSlider(element) {
  const root = typeof element === 'string'
    ? document.querySelector(element)
    : element;

  const items = root.querySelectorAll('.slider__item');
  const prev = root.querySelector('.slider__btn-prev');
  const next = root.querySelector('.slider__btn-next');

  let index = 0;

  function slideTo(newIndex) {
    items[index].classList.remove('slider__item--active');
    index = (newIndex + items.length) % items.length;
    items[index].classList.add('slider__item--active');
  }

  prev.addEventListener('click', () => slideTo(index - 1));
  next.addEventListener('click', () => slideTo(index + 1));
}

simpleSlider('#slider1');
simpleSlider(document.querySelector('#slider2'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question