jqueryjquery-effectsjquery-slider

Jquery Slide Show Slide effect from left to right


I have tried to make a slider to move left to right in a cycle, only the first div works, it moves out and everything comes to a stops.

you can see the working example here

$(document).ready(function () {
    var delay = 3000,
        fade = 1000;
    var banners = $('.banner');
    var len = banners.length;
    var i = 0;
    setTimeout(cycle, delay);

    function cycle() {
        $(banners[i % len]).hide("slide", {
            direction: "left"
        });
        (fade, function () {
            $(banners[++i % len]).show("slide", {
                direction: "right"
            });
            (fade, function () {
                setTimeout(cycle, delay);
            });
        });
    }
});

Thank You


Solution

  • perhaps this is what you need: Updated Fiddle

    first, this code of yours is never called

    (fade, function () {
        $(banners[++i % len]).show("slide", {
            direction: "right"
        });
        (fade, function () {
            setTimeout(cycle, delay);
        });
    });
    

    this cause the cycle function will only trigger once, since you use setTimeout, so in your case which need to loop it over and over every x seconds, it's better to use setInterval, so change

    setTimeout(cycle, delay);
    

    to

    setInterval(cycle, delay);
    

    then for the cycle function, change your code to this

    function cycle() {
        $(banners[i % len]).hide("slide", {
            direction: "left"
        });
        $(banners[++i % len]).show("slide", {
            direction: "right"
        });
    }
    

    and it's done, your code will be working now. But because the .banner is a div which is a block element, the .banner will be in 2 line when the 2nd div showed before the 1st div is hidden, so you need to add style

    position: absolute;
    

    to the .banner so it will show up in the same line