Why does setInterval seem to have scope issues in my jQuery plugin?
I'm sorry this isn't more specific, but I'm having trouble isolating the issue.
I've written a very simple jQuery plugin that scrolls images or other elements through a div, like a carousel, on a set interval. I wanted this plugin to work with multiple instances on one page, but when I call it on multiple elements, only the last initialized element scrolls. I assume the way I'm using setInterval is the cause, but I don't understand why.
The function for scrolling is as follows, and the full source is linked above.
function scrollRight() {
// Don't animate if the mouse is over the scrollah
if (hovering) { return; }
/* If we're at the end, flip back to the first image
* 开发者_JAVA技巧before animating, lest we view blankness in the wrapper
*/
if (position === nChildren) {
position = 0;
$wrapper.css('left', '0px');
}
// Animate to the next view
position++;
$wrapper.animate({
left: position*-width+'px'
}, 1000, 'swing', function() {
// Animation complete.
});
}
setInterval(scrollRight, 5000);
So why do individual instances of this plugin not scroll once more have been initialized?
I think if you change $wrapper = $this.find('.wrapper');
to var $wrapper = $this.find('.wrapper');
it might work.
Learned this the other day from Stack Overflow: variables that don't use the var
keyword are implicitly global in scope, so I think each scroller is overwriting the same global $wrapper
variable.
EDIT: might also want to do var $this = $(this);
.
精彩评论