JSFiddle - React, Tailwind, and code Playground
HTML
<div class="focus-change-set">
<div class="focus-target"></div>
<div class="focus-target"></div>
<div class="focus-target"></div>
<div class="focus-target"></div>
</div>
<!-- UNCOMMENT FOLLOWING BLOCK TO BREAK! -->
<!-- <div class="focus-change-set">
<div class="focus-target"></div>
<div class="focus-target"></div>
<div class="focus-target"></div>
<div class="focus-target"></div>
</div> -->
CSS
.focus-change-set{
display:inline-block;
margin-left:20px;
}
.focus-target{
height:50px;
width:50px;
background:blue;
}
.focus-target.focus, .focus-target:hover{
background:red;
}
JavaScript
(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();
}
});