Reputation:
I am trying to get this slider to auto play in Javascript (jquery) but I can't seem to get it to work, Does anyone know how I can achieve this? Every time I tried something it seemed to break the slider buttons.
jsfiddle version: http://jsfiddle.net/EsdB7/5/
Here is the current code:
jQuery(document).ready(function ($) {
var slideCount = $('#slider ul li').length;
var slideWidth = $('#slider ul li').width();
var slideHeight = $('#slider ul li').height();
var sliderUlWidth = slideCount * slideWidth;
$('#slider').css({ width: slideWidth, height: slideHeight });
$('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });
$('#slider ul li:last-child').prependTo('#slider ul');
function moveLeft() {
$('#slider ul').animate({
left: + slideWidth
}, 200, function () {
$('#slider ul li:last-child').prependTo('#slider ul');
$('#slider ul').css('left', '');
});
};
function moveRight() {
$('#slider ul').animate({
left: - slideWidth
}, 200, function () {
$('#slider ul li:first-child').appendTo('#slider ul');
$('#slider ul').css('left', '');
});
};
$('a.control_prev').click(function () {
moveLeft();
});
$('a.control_next').click(function () {
moveRight();
});
});
Upvotes: 0
Views: 7256
Reputation: 11
Neil's answer is correct, but if you want it to automatically play when the page loads, you can add this to your variable declarations:
var auto = setInterval(moveRight, 1000); // 1000 ms = 1 sec
like so:
var slideCount = $('#slider ul li').length;
var slideWidth = $('#slider ul li').width();
var slideHeight = $('#slider ul li').height();
var sliderUlWidth = slideCount * slideWidth;
var auto = setInterval(moveRight, 1000); // 1000 ms = 1 sec
Upvotes: 1
Reputation: 412
just add the following code -
var auto = setInterval(moveRight, 1000); // 1000 ms = 1 sec
after :
$('a.control_next').click(function () {
moveRight();
});
//any where after the declaration of moveRight function.
whats happening is that, the moveRight function is being called after every 1000 ms.
JS FIDDLE of the edited code
Upvotes: 0