0

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>
dferenc
  • 7,918
  • 12
  • 41
  • 49
Akolix
  • 1
  • 1

1 Answers1

1

You could use an IF statement to detect when the character is at the edge.

With your example your JavaScript would become:

var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39 && guyLeft <= 278) {
guyLeft += 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37 && guyLeft >= 2) {
guyLeft -= 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40 && y <= 278) {
y += 2; guy.style.top = y + "px";
}
else if (e.keyCode == 38 && y >= 2) {
y -= 2; guy.style.top = y + "px";
}

} document.onkeydown = anim;

Here's a working example:

var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39 && guyLeft <= 278) {
guyLeft += 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37 && guyLeft >= 2) {
guyLeft -= 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40 && y <= 278) {
y += 2; guy.style.top = y + "px";
}
else if (e.keyCode == 38 && y >= 2) {
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>