Hi I am relatively new to javascript and jQuery and while trying to create a function the runs in intervals of 100 milliseconds I encountered a problem.I seem to get in the console of firebug and error witch says that clasing() is not defined.This is my code:
$(document).ready(function() {
var prev = $("img.selected").prev();
var curent = $("img.selected");
var next = $("img.selected").next().length ? $("img.selected").next() : $("img:first");
$("img").not(":first").css("display","none");
function clasing() {
curent.removeClass("selected");
next.addClass("selected");
}
setInterval("clasing()",100);
});
What am I doing wrong here?Thank you
You have a scope problem. Your variables (
prev,curentandnext) are accessible inside.readyscope, such as your functionclasing. But when you add this function to be called in a interval, usingsetInterval, this function should be in a Global scope (insidewindowobject). Then, you should declare this function likewindow.clasing = function(){ ... }, but, doing this, the variables declared in.ready()scope will not be accessible running the function outside this scope, so all your variables must be in a global scope too. This should solve your problem.However, this isn’t a good programming practice, you should declare your variables inside
clasingfunction, then they will be accessible only in function scope; And your function must be delcared outside.ready()function, and then you declare the interval inside.ready()function.So, your code should be liek this: