This should solve your problem:
$(document).ready(function () {
var inner = $('.carousel-inner'),
slides = inner.find('li'),
width = slides.eq(0).outerWidth(true),
max = (width * slides.length) - width;
$('#right, #left').on('click', function () {
var currRight = parseInt(inner.css('right'), 10), move;
if (this.id === 'right') {
move = currRight === max ? 0 : currRight+width;
} else {
move = currRight === 0 ? max : currRight-width;
}
inner.animate({ right: move }, 500);
});
});
The top four lines cache elements and set up a few basic variables such as the max right
value that can used and the width
of the slides.
I've then combined the click
events to avoid repetition. The first line of the click event defines currRight
as $('.carousel-inner')
's current CSS right
value as well as move
which is used later on.
if (this.id === 'right'){ /* #right */ }else{ /* #left */ }
checks whether the id
of the clicked element is right
or left
. The code inside the if statement just checks to see whether the slider is at zero (the beginning) or max (the end) and then sets the move
variable to the correct value.
Here it is working: http://jsfiddle.net/mFxcq/10/
Update: To make the slides move on a timer add this after the click event is attached:
function setTimer(){
clearTimeout(window.slideTimer);
window.slideTimer = setTimeout(function(){ $('#right').trigger('click'); }, 5000);
};
setTimer();
Then add setTimer();
right after inner.animate({ right: move }, 500);
and everything will work as expected.
Here it is working: http://jsfiddle.net/mFxcq/14/