benhowdle89
benhowdle89

Reputation: 37464

Function is not defined, failed to load sources jQuery

I have this jquery code:

$(document).ready(function() {
            function slideSwitch() {
                var $active = $('#slideShow IMG.active');

                if ( $active.length == 0 ) $active = $('#slideShow IMG:last');

                var $next =  $active.next().length ? $active.next()
                    : $('#slideShow IMG:first');

                $active.addClass('last-active');

                $next.css({opacity: 0.0})
                    .addClass('active')
                    .animate({opacity: 1.0}, 1000, function() {
                        $active.removeClass('active last-active');
                    });
            }


                setInterval( "slideSwitch()", 5000 );

        });

And it errors with slideSwitch() is not defined?? any ideas?

Upvotes: 0

Views: 185

Answers (2)

Guffa
Guffa

Reputation: 700362

If you use a string with setInterval it will be evaludated in the scope of the window object, and as you declared the function locally in another function, it's not available globally.

Just use the function name instead of a string with code that calls the function:

window.setInterval(slideSwitch, 5000);

This will pass a reference to the function instead of a string, so it doesn't rely on the name of the function when it's called.

Upvotes: 5

Neil
Neil

Reputation: 5780

Try declaring your function outside the ready event. I don't think there's anything wrong syntactically, though might be that it can't find the function in that scope.

Upvotes: 0

Related Questions