2

I have this javascript code:

$(function(){
  var currentCarouselItem = 1; //set carousel to first slide
  var runCarousel = 1;

  $(window).load(function(){    
    setTimeout('autoScroll()', 10000);
  });

  function autoScroll(num){
    if (runCarousel == 1) {
      $('.carouselItem.' + currentCarouselItem).animate({left: '975px'}, 'slow', function(){
        $(this).removeClass('active');
        $(this).attr('style','');
        var nextItem = currentCarouselItem + 1;
        if (nextItem == 7) {
            nextItem = 1;
        }
        $('.carouselItem.' + nextItem).animate({left: '110px'}, 'slow', function(){
          $(this).addClass('active');
        })
      })
    }   
  }
})

Whenever I run the site it throws a console error: Uncaught ReferenceError: autoScroll is not defined

Any idea why it thinks it is not defined?

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
chromedude
  • 4,246
  • 16
  • 65
  • 96

6 Answers6

4
setTimeout('autoScroll()', 10000);

Why put it in quotes?

setTimeout(autoScroll, 10000);

That's for starters.

Additionally, you have scoping issues here.

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
3

I could try answering it for you, but I think this guy does a lot better job:

JQuery, setTimeout not working

Community
  • 1
  • 1
Marquis
  • 531
  • 1
  • 4
  • 13
1

I think this is because your autoScroll function is inside closure created by outermost $(function(){}). Therefore eval (used to evaluate your string in setTimeout) can't find it, as it runs in a 'global' scope.

You can move the definition of autoScroll outside.

Also, as jcolebrand suggested, remove quotes.

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
1

I think it is because when you pass in a string as the first argument for setTimeout() that javascript basically runs eval() from the global scope on that string. autoScroll lives within the scope of $(function() { }) and therefore can't be "seen" from the global scope.

Try changing it to setTimeout(autoScroll, 10000);

jessegavin
  • 74,067
  • 28
  • 136
  • 164
1

There a couple of problems with your code, but the reason that the autoScroll function is not defined is that it defined within the scope of your document ready function, but is executed via eval after the document ready has gone out of scope without the proper closure.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
0
$('.carouselItem.' + currentCarouselItem).animate({left: '975px'}, 'slow', function(){
                $(this).removeClass('active');
                $(this).attr('style','');
                var nextItem = currentCarouselItem + 1;
                if (nextItem == 7) {
                    nextItem = 1;
                }
                $('.carouselItem.' + nextItem).animate({left: '110px'}, 'slow', function(){
                    $(this).addClass('active');

                });
            });

For starters you need a semi colon at the end of functions like this,

williamsandonz
  • 15,864
  • 23
  • 100
  • 186