I
I
Ivan2019-01-21 23:14:19
JavaScript
Ivan, 2019-01-21 23:14:19

How to optimize and minify javascript code in a slider?

Gentlemen, I ask for your help in optimizing and refactoring JS code in the slider.
There is this markup:

<body>
  <div class="slider-wrapper-1" id="slide-wrapper">
    <div class="slider-controls">
          <button class="control-button" id="btnSlideOne"><span class="visually-hidden">Первый слайд</span></button>
          <button class="control-button" id="btnSlideTwo"><span class="visually-hidden">Второй слайд</span></button>
          <button class="control-button" id="btnSlideThree"><span class="visually-hidden">Третий слайд</span></button>
    </div>
  <!-- разметка -->
  </div>
</body>

And here's the JS:
var slideWrapper = document.querySelector('#slide-wrapper');
var btnSlideArray = document.querySelectorAll('.control-button');

function slideChange(indexSlideOn, slideLength) {
  if (indexSlideOn >= slideLength) return;
  for (var i = 0; i < slideLength; i++) {
    if (i === indexSlideOn) {
      slideWrapper.classList.add('slider-wrapper-' + (i + 1));
    } else {
      slideWrapper.classList.remove('slider-wrapper-' + (i + 1));
    }
  }
}

btnSlideArray[0].addEventListener('click', function(evt) {
  evt.preventDefault();
  slideChange(0, btnSlideArray.length);
});

btnSlideArray[1].addEventListener('click', function(evt) {
  evt.preventDefault();
  slideChange(1, btnSlideArray.length);
});

btnSlideArray[2].addEventListener('click', function(evt) {
  evt.preventDefault();
  slideChange(2, btnSlideArray.length);
});

This code is working, classes are switched, everything works. My question is this:
looking at the end of the JS code, I understand that the click events on the buttons can somehow be combined and made more universal (so that when changing the number of slides you don’t have to change the JS code), that’s just my knowledge, unfortunately, so far not enough to figure out how to do it.
I will be glad to help with this code and hints where and what I should read and study, so that there are no such questions in the future.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NonameMeTrue, 2019-01-21
@IvanPsarev

[].forEach.call(btnSlideArray, function(el, i) {
  el.addEventListener('click', function(evt) {
    evt.preventDefault();
    slideChange(this.valueOf(), btnSlideArray.length);
  }.bind(i));
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question