Reputation: 13
I can't understand. In Chrome debugger it works, but when I turn it off and refresh the page, my div is clear.
<script type="text/javascript">
$(document).ready(function() {
function banner_change(span) {
if ($(span).hasClass('show')) {
$(span).removeClass('show');
}
}
$('div#spec_banner span').each(function () {
if (!$(this).hasClass('show')) {
$(this).addClass('show')
}
setTimeout(banner_change(this), 5000);
});
});
</script>
Thank you for answering.
Upvotes: 0
Views: 6144
Reputation: 7265
get the function out of document ready for it to work properly
Upvotes: 0
Reputation: 171669
several problems , syntax and scope
When using setTimeout without an anonymous function, syntax is:
setTimeout(banner_change, 5000); /* no () */
To pass arguments need to do:
setTimeout(function(){
banner_change(this);
}, 5000);
But also, back to scope, this
has lost context inside setTimeout ( is now likely window
) so need to assign to variable outside of setTimeout
$('div#spec_banner span').each(function () {
if (!$(this).hasClass('show')) {
$(this).addClass('show')
}
var span =this
setTimeout(function(){
banner_change(span);
}, 5000);
});
Upvotes: 3
Reputation: 8225
you need to pass function reference not function invocation result.
setTimeout( $.proxy(banner_change, this), 5000);
$.proxy wrapper for the function reference will ensure your function is invoked with the "this" context.
Upvotes: 0
Reputation: 1815
This is an issue:
setTimeout(banner_change(this), 5000);
You're actually calling banner_change here - try
setTimeout(function(){
banner_change('div#spec_banner span');
}, 5000);
The call you were originally doing was executing banner_change
immediately and passing the return value to setTimeout
Upvotes: 1