JSFiddle - React, Tailwind, and code Playground
by Barry Margolin
HTML
<div class="focus-change-set" id="f1">
<div class="focus-target" id="f1t1"></div>
<div class="focus-target" id="f1t2"></div>
<div class="focus-target" id="f1t3"></div>
<div class="focus-target" id="f1t4"></div>
</div>
<!-- UNCOMMENT FOLLOWING BLOCK TO BREAK! -->
<div class="focus-change-set" id="f2">
<div class="focus-target" id="f2t1"></div>
<div class="focus-target" id="f2t2"></div>
<div class="focus-target" id="f2t3"></div>
<div class="focus-target" id="f2t4"></div>
</div>
CSS
.focus-change-set {
display:inline-block;
margin-left:20px;
}
.focus-target {
height:50px;
width:50px;
background:blue;
}
.focus-target.focus {
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
function _changeFocus (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();
}
});