this is a continuation of my question yesterday regarding an automatic jQuery image slider which you can find here - Jquery automatic image slider.
I've added a couple of media queries into my css and am trying to mirror them with an 'if / if else' statement in the javascript, however at the moment it's only working for the second section of the statement. For both others the slide appears to move 620px to the left, leaving a section of another picture in the frame, but still resets to 'margin: 0' after the last slide.
There is also a lot of repetition in the code which ideally I would like to get rid of but when I tried including only the width variable in the 'if' statement the code didn't run.
I'm stumped! Any help would be greatly appreciated.
$(document).ready(function() {
//INDEX IMAGES SLIDER
$(function() {
if($('#slider').width() > 760) {
//configuration
var width = 720;
var speed = 1000;
var pause = 2000;
var current = 1;
//cache DOM
var $slider = $('#slider');
var $slides = $slider.find('#slides');
var $slide = $slides.find('.slide');
setInterval(function() {
$slides.animate({'margin-left': '-='+width}, speed, function() {
current++;
if (current === $slide.length) {
current = 1;
$slides.css('margin-left', 0);
}
});
}, pause);
} else if($('#slider').width() <= 760) {
var width = 620;
var speed = 1000;
var pause = 2000;
var current = 1;
//cache DOM
var $slider = $('#slider');
var $slides = $slider.find('#slides');
var $slide = $slides.find('.slide');
setInterval(function() {
$slides.animate({'margin-left': '-='+width}, speed, function() {
current++;
if (current === $slide.length) {
current = 1;
$slides.css('margin-left', 0);
}
});
}, pause);
} else {
var width = 520;
var speed = 1000;
var pause = 2000;
var current = 1;
//cache DOM
var $slider = $('#slider');
var $slides = $slider.find('#slides');
var $slide = $slides.find('.slide');
setInterval(function() {
$slides.animate({'margin-left': '-='+width}, speed, function() {
current++;
if (current === $slide.length) {
current = 1;
$slides.css('margin-left', 0);
}
});
}, pause);
};
});
});
#slider {
width: 720px;
height: 400px;
overflow: hidden;
margin: 100px auto;
}
#slider #slides {
display: block;
width: 2880px;
height: 400px;
margin: 0;
padding: 0;
}
#slider .slide {
float: left;
list-style: none;
height: 400px;
width: 720px;
}
#slider .slide img {
width: 100%;
}
@media only screen and (max-width: 760px) {
#slider {
width: 620px;
}
#slider .slide {
width: 620px;
}
#slider .slide img {
width: 620px;
}
}
@media only screen and (max-width: 650px) {
#slider {
width: 520px;
}
#slider .slide {
width: 520px;
}
#slider .slide img {
width: 520px;
}
}
<div class="page-container">
<div id="slider">
<ul id="slides">
<li class="slide"><img src="images/sp_1.png"></li>
<li class="slide"><img src="images/ss_1.jpg"></li>
<li class="slide"><img src="images/sd_1.jpg"></li>
<li class="slide"><img src="images/sp_1.png"></li>
</ul>
</div>
</div>