0
I’d like to know how to make a div
lively (I have function JQuery keydown
that moves a div) but the div
comes off the screen and I’d like it to be only 20 px of the margins.
I have already put this div (div1) inside another div (div2) and put position:relative
and overflow:hidden
in div2 but still div1 leaves div2.
I have also tried to make some validations of the position of the div1 but unfortunately without success.
PS: Use keyboard arrows to move the div1.
I leave down 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>
<div class="box"></div>
You have to analyze the
left
andtop
by code and do not let animate if the next animation crosses the limits– Isac