JSFiddle - React, Tailwind, and code Playground
by gtbhopale
HTML
<button onclick="animateScript()" value="Play">
Play
</button>
<button onclick="stopAnimate()"value="Stop">
Stop
</button>
<div id="demo">
<p id="image" >
</p>
</div>
<script>
var tID; //we will use this variable to clear the setInterval()
function stopAnimate() {
clearInterval(tID);
} //end of stopAnimate()
function animateScript() {
var position = 395; //start position for the image slicer
const interval = 100; //100 ms of interval for the setInterval()
const diff = 395; //diff as a variable for position offset
tID = setInterval(() => {
document.getElementById("image").style.backgroundPosition =
`-${position}px 0px`;
//we use the ES6 template literal to insert the variable "position"
if (position < 1536) {
position = position + diff;
}
//we increment the position by 256 each time
else {
position = 395;
}
//reset the position to 256px, once position exceeds 1536px
}, interval); //end of setInterval
} //end of animateScript()
</script>
CSS
#image {
height: 395px;
width: 395px;
background: url('https://i.pinimg.com/originals/b4/98/45/b49845d28401378711d4f10524a4bb52.png') 0px 0px;
}