I'm currently working on creating an image slider that is responsive to screen size, specifically functioning when the screen width is less than 640 pixels. For wider screens, it should display 3 items with 33% width to fit nicely. I have been able to make the slider slide, but when resizing back to a larger size and clearing the interval, the slider freezes and leaves distorted images. Is there a way to restrict the slider to work only on one screen size? The code provided below showcases my current progress, however, I have not found any similar tasks or examples online.
Jquery Code
var slider = $("#slider")
var container = $("#slides");
var slides = $(".slides");
var len = 3;
var current = 1;
var width = '100%';
var animationSpeed = 3000;
var pause = 3000;
var interval;
function startSlider() {
interval = setInterval(function () {
container.animate({
'margin-left': '-=' + width
}, animationSpeed, function () {
if (++current === len) {
current = 1;
container.css('margin-left', 0);
}
});
}, pause);
}
function stopSlider(){
clearInterval(interval);
}
function checkView() {
var winWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if(winWidth < 640 ) {
startSlider();
} else{
stopSlider();
}
}
checkView();
$(window).resize(checkView);
Html Code
<section id="slider" class="slider clearfix">
<nav class="nav-arrow">
<img id="#prev" class="prev" src="images/1463330656_br_prev.png" alt="prev">
<img id="#next" class="next" src="images/1463330669_br_next.png" alt="next">
</nav>
<ul id="slides" class="slides">
<li><img class="slide" src="images/box.jpg" alt=""></li>
<li><img class="slide" src="images/bridge.jpg" alt=""></li>
<li><img class="slide" src="images/smile.jpg" alt=""></li>
</ul>
</section>