I made this script which moves a smaller div inside it's parent container, but I need it so that it doesn't go past the boundaries of the parent (represented by the 1px black line border). Could someone help me?
var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39) {
guyLeft += 2;
guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37) {
guyLeft -= 2;
guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40) {
y += 2;
guy.style.top = y + "px";
}
else if (e.keyCode == 38) {
y -= 2;
guy.style.top = y + "px";
}
}
document.onkeydown = anim;
#container {
height:300px;
width:300px;
outline: 2px solid black;
position:relative;
}
#guy {
position:absolute;
height:20px;
width:20px;
outline: 1px solid black;
background-color:red; left: 0;
}
<div id="container">
<div id="guy"></div>
</div>