JSFiddle - React, Tailwind, and code Playground
HTML
<div id="container">
<div id="block"></div>
</div>
<input id="trigger" type="button" value="Start Animation" />
CSS
#trigger {display:block;}
#container {position:relative; overflow:hidden; background:#f6e5d4; height:20px; width:300px; margin:4px;}
#block {position:absolute; top:0; left:0; height:20px; width:20px; background:#900;}
JavaScript
var isAnimating = false;
//Set a trigger to start the animation.
$('#trigger').click(function(){
// Is the block already animating?
if(isAnimating){
// add a check to make sure the block isn't already close enough to stop on its own.
if($('#block').offset().left < ($('#container').width() - $('#block').width())){
// Stop the animation.
$('#block').stop();
// Create new animation.
$('#block').animate({left:'+=76'}, 100, 'linear', function(){
isAnimating = false;
// Update button text
$('#trigger').attr('value', 'Start Animation');
});
}
} else {
// reset the start position (for this demo)
$('#block').css({left:0});
// Update button text
$('#trigger').attr('value', 'Stop Animation');
isAnimating = true;
$('#block').animate({left:280}, 5000, 'linear', function(){
isAnimating = false;
// Update button text
$('#trigger').attr('value', 'Start Animation');
});
}
});