4

I've built a simple carousel with left and right scroll. Now I want to scroll automatically every 5 seconds. Here's my code:

function carousel(){
        $j('#carousel_ul li:first').before($j('#carousel_ul li:last'));

        $j('#right_scroll img').click(function(){

            var item_width = $j('#carousel_ul li').outerWidth() + 10;

            var left_indent = parseInt($j('#carousel_ul').css('left')) - item_width;

            $j('#carousel_ul:not(:animated)').animate({'left' : left_indent},800, 'easeOutExpo',function(){

                $j('#carousel_ul li:last').after($j('#carousel_ul li:first'));

                $j('#carousel_ul').css({'left' : '-750px'});
            });
        });

        $j('#left_scroll img').click(function(){

            var item_width = $j('#carousel_ul li').outerWidth() + 10;

            var left_indent = parseInt($j('#carousel_ul').css('left')) + item_width;

            $j('#carousel_ul:not(:animated)').animate({'left' : left_indent},800, 'easeOutExpo',function(){

            $j('#carousel_ul li:first').before($j('#carousel_ul li:last'));

            $j('#carousel_ul').css({'left' : '-750px'});
            });

        });
}

How do I achieve that? Thanks in advance :)

Mauro

Mauro74
  • 4,686
  • 15
  • 58
  • 80

2 Answers2

12

You can use setInterval. Look:

window.setInterval(event, 5000);

And function event would be

function event() {
 $j("#right_scroll img").click();
}

EDIT:

Tks @cris! setTimeout calls only one time. I changed to setInterval.

Tks @bears! Now I pass a function to setInterval.

Topera
  • 12,223
  • 15
  • 67
  • 104
  • setTimeout will do it only once. setInterval will call the function over and over and over... setInterval is better for this situation. – Gabriel Aug 23 '10 at 17:04
  • 1
    *PLEASE* don't pass strings to `setInterval` and `setTimeout`! Pass a function: `setInterval(event, 5000);` and `setInterval(function () {$j("#right_scroll img").click();}, 5000);` – Matt Ball Aug 23 '10 at 17:07
  • Thanks Topera! was easier than I imagined! :) – Mauro74 Aug 24 '10 at 09:02
12
var i = setInterval(carousel, 5000)

And to stop it later:

clearInterval(i);
Chris
  • 27,596
  • 25
  • 124
  • 225