Reputation: 2959
I have build the following carousel but when I reach the last image or from first image I want to go back I want to show the image needs to show. For example when you reach the last image when you click right arrow to show the first image.
Have anyone any idea how to improve this?
https://jsfiddle.net/6nhuk7vm/
jQuery(document).ready(function ($) {
var currentPosition = 0;
var slideWidth = 1200;
var slides = $('.slide');
var numberOfSlides = slides.length;
var slideShowInterval;
var speed = 7000;
slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>')
slides.css({ 'float' : 'left' });
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
$('#slideshow')
.append('<span class="nav" id="leftNav"></span>')
.append('<span class="nav" id="rightNav"></span>');
manageNav(currentPosition);
$('.nav').bind('click', function() {
currentPosition = ($(this).attr('id')=='rightNav')
? currentPosition+1 : currentPosition-1;
manageNav(currentPosition);
clearInterval(slideShowInterval);
slideShowInterval = setInterval(changePosition, speed);
moveSlide();
});
function manageNav(position) {
$('#leftNav').css('position','absolute')
$('#rightNav').css('position','absolute')
}
function changePosition() {
if(currentPosition == numberOfSlides - 1) {
currentPosition = 0;
manageNav(currentPosition);
} else {
currentPosition++;
manageNav(currentPosition);
}
moveSlide();
}
function moveSlide() {
$('#slidesHolder')
.animate({'marginLeft' : slideWidth*(-currentPosition)});
}
});
Upvotes: 2
Views: 123
Reputation: 1745
I fixed your slider. Fiddle: JSFIDDLE
if(currentPosition > numberOfSlides-1){
currentPosition = 0;
}
if(currentPosition < 0){
currentPosition = numberOfSlides-1;
}
Just added a couple of if's =)
Upvotes: 0
Reputation: 17707
The standard way to make a 'carousel' effect, to 'wrap' around the right/left side of a system, is to use a modulo %
.
Consider your code:
currentPosition = ($(this).attr('id')=='rightNav') ? currentPosition+1 : currentPosition-1;
That adds a position for right, and removes one for left. Now, we need to "bound/wrap" it inside the limits. This is easy, with:
currentPosition = (currentPosition + numberOfSlides) % numberOfSlides;
What does that do?
If the currentPosition is -1, it adds the full amount, and you end up with numberOfSlides - 1
and the modulo has no effect.
If the currentPosition is more than 0 it will become a larger-than-numberOfSlides value, and the modulo (remainder) function will restore it's proper value.
Upvotes: 2