I have the following small plugin which shifts class of 'focus'
between a set of elements.
This issue is, If I have multiple sets on a single page, with a new instance of the plugin applied to each set, there appears to be a conflict between the setTimeout
function not staying within the plugin instance context.
(function($){
$.fn.focusChanger = function(){
return this.each(function(){
//VARIABLES
var $this = $(this),
$targets = $this.find('.focus-target'),
numTargets = $targets.length,
autoSpeed = 2500,
autoChangeT = setTimeout(_autoChange, 500),
currentIndex = numTargets;
/////////////// Handlers ///////////////
$this.hover(
function () {
//stop auto-changing
_autoReset();
},
function () {
autoChangeT = setTimeout(_autoChange, 500);
}
);
/////////////// Functions ///////////////
//Change Slide
_changeFocus = function(newIndex){
$targets.eq(currentIndex).removeClass("focus");
$targets.eq(newIndex).addClass("focus");
currentIndex = newIndex;
};
//auto slide changer
function _autoChange() {
console.log($this);
var newIndex;
if(currentIndex >= numTargets - 1){
newIndex = 0;
}else{
newIndex = currentIndex + 1;
};
_changeFocus(newIndex);
autoChangeT = setTimeout(_autoChange, autoSpeed);
};
// stop auto slide changer
function _autoReset() {
clearTimeout(autoChangeT);
$targets.eq(currentIndex).removeClass("focus");
};
});//end each (plugin)
};// end fn
})(jQuery);
$(document).ready(function(){
if($.fn.focusChanger){
$('.focus-change-set').focusChanger();
}
});
The above fiddle shows a working version of the plugin when applied to a single instance. Uncomment the second HTML block inside to see it break.
I have done my best to understand the following issue, but haven't been able to apply it to my plugin setup, as I am not passing this
into the setTimout.
- https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout#The_%27this%27_problem
- Pass correct "this" context to setTimeout callback?
- jQuery plugin, context and setTimeout
How can I keep the instances of the plugin (and I suspect setTimeout
specifically) from interfering with each other?