shadowayex Posted March 20, 2011 Share Posted March 20, 2011 I have an array of DOM items and I have this line inside of a for loop: setInterval(function() { items[i].style.top = items[i].offsetTop + 1 + "px"; }, interval); I get an error telling me items does not exist. I'm thinking it's a scoping problem or something of the sort. I was wondering how to go about getting at these DOM items in the anonymous function inside the setInterval function. Link to comment Share on other sites More sharing options...
Synook Posted March 21, 2011 Share Posted March 21, 2011 What's the rest of the code? Link to comment Share on other sites More sharing options...
justsomeguy Posted March 21, 2011 Share Posted March 21, 2011 By the time that function runs, the loop is finished and i is set to one more than the length of the array, so that's why items doesn't exist. items[i - 1] is the last element in the array at that point. A closure is one way to handle that: function (el){ setInterval(function() { el.style.top = el.offsetTop + 1 + "px"; }, interval);}(items[i]); Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.