I would like to know how to make a div
animated (I have JQuery keydown
function that moves a div) but div
exits the screen and I would like it to be up to 20 px from the margins.
I already exprimentei put this div (div1) inside another div (div2) and put position:relative
and overflow:hidden
in div2 but even then div1 exits div2.
I have also exprimoi to do some validations of the div1 position but unfortunately without success.
PS: Use the arrow keys to move the div1.
I leave below my code:
$(document).keydown(function(e){
//var pos = $(".box").position();
switch (e.which){
case 37: //left arrow key
$(".box").finish().animate({
left: "-=50"
});
break;
case 38: //up arrow key
$(".box").finish().animate({
top: "-=50"
});
break;
case 39: //right arrow key
$(".box").finish().animate({
left: "+=50"
});
break;
case 40: //bottom arrow key
$(".box").finish().animate({
top: "+=50"
});
break;
}
});
.box{
width: 100px;
height: 100px;
position: relative;
margin: 200px auto 0;
background: yellowgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="box"></div>