Error is:
switchDiv is not defined
JSFiddle example here: http://jsfiddle.net/9s5Px/11/
Here is the HTML markup:
<div id="container">
<div class="foo">
<p>Div A</p>
</div>
<div class="foo">
<p>Div B</p>
</div>
<div class="foo">
<p>Div C</p>
</div>
</div>
And the JavaScript:
$('.foo').fadeOut('fast');
var count = $('.foo').length;
console.log(count);
var currentItem = 0;
function switchDiv() {
$('.foo').get(currentItem).fadeOut();
if (currentItem < count - 1) {
$('.foo').get(currentItem + 1).fadeIn();
}
else {
$('.foo').get(currentItem).fadeOut();
currentItem = 0;
$('.foo').get(0).fadeIn();
}
}
setTimeout("switchDiv()", 5000 );
3 Answers 3
Your string of code that you pass in to setTimeout does not have access to your local closure. It is being evaled globally.
Pass it the function itself, not a string:
setTimeout(switchDiv, 5000);
See here, no errors.
4 Comments
You have a scoping issue in your jsfiddle. Not sure about the actual code, but since you are not showing how that js is being I called I assume it is the same problem.
Note that jsfiddle will execute the code you specified inside $(document).ready() handler (see options on top left), and so you switchDiv will be defined in there. Where as your timeout is looking for switchDiv on global object, and is effectively this setTimeout("window.switchDiv()", 5000);
The solution is to either pass function reference to the setTImeout or define setTimeout in the global scope like this.
As a side note: The get() function returns actual DOM object. WHat you probably looking for is eq(), but note that eq is 1-based.
2 Comments
$(document).ready(), from the options on the left...$(document).ready() handler to jsfiddle explicitly will still work. That is because jQuery is smart enough to run ready handler immediately if the DOM is already ready.two issues here:
1.use
setTimeout(switchDiv, 5000);
instead of evaluating a string.
2.inside switchDiv, you used get function to return a dom element in a jQuery object, and thus the fadeIn and fadeOut methods are not applicable.
Modified src:
$('.foo').fadeOut('fast');
var count = $('.foo').length;
console.log(count);
var currentItem = 0;
function switchDiv() {
$($('.foo').get(currentItem)).fadeOut();
if (currentItem < count - 1) {
$($('.foo').get(currentItem + 1)).fadeIn();
}
else {
$($('.foo').get(currentItem)).fadeOut();
currentItem = 0;
$($('.foo').get(0)).fadeIn();
}
}
setTimeout(switchDiv, 5000 );