I am building a function to update a HTML node’s background position at a regular basis. The function works for a single node, but when called upon multiple node (in the following example), only the last node is affected by this function.
According to the alert(index) within the function, setInverval() is called for each node.
I cannot figure out why it doesn’t take effect.
var bgImgAnimate = function (settings) {
$.each(settings.nodeList, function (index, node) {
thisNode = $(node);
var thisPosition;
setInterval(function () {
alert(index);
//calculate the position before position the image
thisPosition = - settings.frameWidth * settings.currentFrame;
thisNode.css('backgroundPosition', (thisPosition + 'px') + ' ' + (settings.verticalPos + 'px'));
}, settings.interval);
});
};
var settings = {
nodeList: $('#star1, #star2, #star3'),
verticalPos: 0,
currentFrame: 1,
frameWidth: 26,
startTime: 2,
frameNumber: 10,
interval: 200
}
bgImgAnimate(settings);
Your variable
thisNodeis global, so once you execute your function you quickly loop through all three elements (what you call nodes), but when that’s done, all three functions that will execute at the interval will refer to a single element (and therefore only that one will be changed, the fact that your alerts showed you the correct answer, is because each alert references a differently and correctly scopedindexvalue).Simple fix, change:
to:
http://jsfiddle.net/GqNgs/2/
As an aside, it would probably be more scalable to set only one interval function, and each time it’s called move the background (or do whatever manipulation you want) on all elements, rather than an interval for each element.