3

Please i need help sliding images using jquery back and forth, or just to go round. right now it slides upto the last element and rushes back to the first div and begins again, not beautiful at all,i know i should call back a function to do that but i keep getting mistakes. thanks in advance, this is my jquery code below

$(document).ready(function() {
    var currentPosition = 0;
    var slideWidth = 190;
    var slides = $('.slider_move');
    var numberOfSlides = slides.length;
    var slideShowInterval;
    var speed = 5000;

    slideShowInterval = setInterval(changePosition, speed);                 
    slides.wrapAll('<div id="slidesHolder"></div>')                 
    slides.css({ 'float' : 'left' });                   
    $('#slidesHolder').css('width', slideWidth * numberOfSlides);  

    function changePosition() {
        if(currentPosition == numberOfSlides - 1) {
            currentPosition = 0;
        } else {
            currentPosition++;
        }
        moveSlide();
    }                   
    function moveSlide() {
            $('#slidesHolder')
              .animate({'marginLeft' : slideWidth*(-currentPosition)});
    }
});​
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
job kwemoi
  • 65
  • 1
  • 10

1 Answers1

2

Instead of:

if(currentPosition == numberOfSlides - 1) {
    currentPosition = 0;
} else {
    currentPosition++;
}

You need to move the first slide to the very end (and adjust the position of the container at the same time):

if (currentPosition > 0) {
    $('#slidesHolder').css('marginLeft',0)
        .children().first().appendTo('#slidesHolder');
} else {
    currentPosition += 1;
}

http://jsfiddle.net/mblase75/qatry/

Or, to optimize the whole thing a little more, you can eliminate the currentPosition variable and the moveSlide sub-function, and just use a callback in the .animate method:

function changePosition() {
    $('#slidesHolder').animate({
        'marginLeft': 0-slideWidth
    }, function() {
        $('#slidesHolder').css('marginLeft', 0)
            .children().first().appendTo('#slidesHolder');
    });
}

http://jsfiddle.net/mblase75/8vaCg/

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • Won't work -- the first slide will always be the same, you need to remove it and then append it. – Chris Aug 28 '12 at 15:14
  • Blazemonger still not working, this is where am doing it http://greencredit.webstyle.ru/ down near the footer, i just need them to slide to the end and back or to go round without stopping – job kwemoi Aug 28 '12 at 15:27
  • @Blazemonger thanks a lot, it works, i know know how to use append, should get more practise! have a great day! – job kwemoi Aug 29 '12 at 07:10