Answer the question
In order to leave comments, you need to log in
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>
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);
});
Answer the question
In order to leave comments, you need to log in
[].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 questionAsk a Question
731 491 924 answers to any question