Greetings to all the brilliant minds on Stack Overflow!
I have been given a school assignment that requires me to create a basic animation using CSS and JavaScript.
I set up a large outer div and added a smaller div inside it. Using JavaScript, I managed to move the smaller div around the larger one by utilizing the onkeypress event in JS.
However, I am facing an issue that I can't seem to resolve – how do I make the smaller div stop when it reaches the border of the larger div? Currently, in my code, it disappears once it crosses the outer div's boundaries.
Strangely enough, I can't get it to function properly when using the built-in snippet feature on this site. It works flawlessly in WebStorm 11! Any tips or advice would be highly appreciated. Thank you in advance!
< script >
//Declare Variables
var test = document.getElementById("test");
var object = document.getElementById("object");
var posx = 200;
var posy = 200;
var width = 100;
var height = 100;
var rotate = 0;
//On KeyDown
document.onkeydown = function keyPress(event) {
var x = event.which;
var speed = 5;
switch (x) {
case 38:
test.innerHTML = "Up";
posy -= speed;
object.style.top = posy + "px";
break;
case 39:
test.innerHTML = "Right";
posx += speed;
object.style.left = posx + "px";
break;
case 40:
test.innerHTML = "Down";
posy += speed;
object.style.top = posy + "px";
break;
case 37:
test.innerHTML = “Left”;
posx -= speed;
object.style.left = posx + “px”;
break;
case 90:
width += 1;
height += 1;
test.innerHTML = "Z";
object.style.width = width + "px";
object.style.height = height + "px";
break;
case 88:
test.innerHTML = "X";
width -= 1;
height -= 1;
object.style.width = width + "px";
object.style.height = height + "px";
break;
case 65:
rotate += 1;
object.style.transform = "rotate('rotate')";
}
< /script>
<style> * {
margin: 0;
padding: 0;
}
#myDiv {
background-color: #005f5f;
width: 500px;
min-height: 500px;
position: relative;
overflow: hidden;
display: block;
}
#object {
width: 100px;
height: 100px;
background-color: red;
position: relative;
top: 200px;
left: 200px;
display: block;
}
</style>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<title>Lesson #2</title>
</head>
<body>
<h1>Lesson #2</h1>
<div id="myDiv>
<div id="object"> </div>
</div>
<div id="test">
</div>
</body>
</html>