JSFiddle - React, Tailwind, and code Playground
by eTiger13
HTML
<div id="boundingBox">
<div id="imove"></div>
</div>
CSS
#boundingBox
{
position: relative;
width: 200px;
height: 200px;
border: 1px solid blue;
}
#imove
{
background: green;
display:block;
width: 100px;
height:100px;
position:absolute;
top:50px;
left:50px;
}
JavaScript
$(document).keyup(function(e) {
var $box = $('#imove');
$box.text(e.keyCode+ ' '+parseInt($box.css('left')));
if ( e.keyCode == 39 )
{
if ( parseInt($box.css('left')) + 2 > 99 )
{
$box.animate
({
left: '+=4'
},
100,
function ()
{
$box.animate
({
left: '-=4'
},
100);
});
}
else
{
$box.animate({
left: '+=2'
}, 200);
}
}
else if ( e.keyCode == 37 )
{
if ( parseInt($box.css('left')) - 2 < 1 )
{
$box.animate
({
left: '-=4'
},
100,
function ()
{
$box.animate
({
left: '+=4'
},
100);
});
}
else
{
$box.animate({
left: '-=2'
}, 200);
}
}
});