JSFiddle - React, Tailwind, and code Playground
by Neil Daley
HTML
<div id='position'>position</div>
<p><button id="go">Stop </button></p>
<img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQrceArBJtODC7UBjnT9Ih6ATEbkkfqBWqqXs67L1lryVMr0La0" width:"800px" height:"800px" />
<div class='ball'>
<img id='ball' src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTlhfp_pfoAI2VnTCi6gLk73D1cTD_Tf-xEFF2DSaIfxOoJu5hGgg" width='100' height='100' />
</div>
CSS
.ball {
position: absolute;
top: 100px;
left:50px;
width: 200px;
height:200px;
background-color: transparent;
}
.wall {
position: absolute;
top:150px;
left:100px;
width: 1000px;
height:850px;
background-color: yellow;
}
JavaScript
var timerInterval = 100;
var timer = window.setInterval(function() { ballTimer() },
timerInterval);
$( "#go" ).click(function() {
window.clearInterval(timer);
});
function ballTimer()
{
moveBall($('.ball'));
}
function moveBall(obj)
{
var left = obj.offset().left;
var top = obj.offset().top;
var moveDuration = 50;
$('#position').html('left:' + left + ' top:' + top);
if ((left <= 250)&&(top<=100))
{
obj.animate({ "left": "+=10px" }, moveDuration );
return;
}
if ((left >= 250)&&(top<=250))
{
obj.animate({ "top": "+=10px" }, moveDuration );
return;
}
if ((left >= 50)&&(top>=250))
{
obj.animate({ "left": "-=10px" }, moveDuration );
return;
}
if ((left<=50)&&(top>=100))
{
obj.animate({ "top": "-=10px" }, moveDuration );
}
}