I am seeking guidance on how to reset an object to its initial position (0) once it exits the browser window. Currently, I have an image that moves when you click on the up/down/left/right buttons, but it eventually extends beyond the browser window.
Below is the code snippet I am currently working with:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<style>
img {
position: absolute;
top: 500px;
left: 100px;
}
.buttons {
background-color: aliceblue;
margin: 0 auto;
display: flex;
justify-content: center;
}
</style>
<script type="text/javascript">
function moveBall(direction) {
var moveDistance = parseInt(document.getElementById('box').value);
var currentTop = parseInt(document.getElementById('ball').getBoundingClientRect().top);
var currentLeft = parseInt(document.getElementById('ball').getBoundingClientRect().left);
switch (direction){
case 'up':
var newTop = currentTop - moveDistance;
var newTopString = newTop + "px";
document.getElementById('ball').style.top = newTopString;
break;
case 'right':
var newRight = currentLeft + moveDistance;
var newRightString = newRight + "px";
document.getElementById('ball').style.left = newRightString;
break;
case 'down':
var newDown = currentTop + moveDistance;
var newDownString = newDown + "px";
document.getElementById('ball').style.top = newDownString;
break;
case 'left':
var newLeft = currentLeft - moveDistance;
var newLeftString = newLeft + "px";
document.getElementById('ball').style.left = newLeftString;
break;
}
}
</script>
</head>
<body>
<img src="images/ball.png" alt="Ball" id="ball" width="100px" height="100px">
<div class="buttons">
<input id="box" type="number">
<button id="up" onClick="moveBall('up')">Up</button>
<button id="right" onClick="moveBall('right')">Right</button>
<button id="down" onClick="moveBall('down')">Down</button>
<button id="left" onClick="moveBall('left')">Left</button>
</div>
</body>
</html>
I believe utilizing innerWidth and innerHeight might help in achieving this, but I need some assistance in implementing it.