Session 7

Exercise

Take the existing animation-problem code and extend it such that the animated div moves to the right of the display and bounces back in the leftward direction when it hit the rightmost edge of the broweser window. Equivalently, the div should bounce again back in the opposite direction when the div hits the left-hand edge of the browser window. You do not need to implement any other functionality; indeed, to do so would be to jump the gun on the sequence of exercises that follow this one. You do, in this case, need to look up the way to detect the right-hand edge of the browser window (more accurately, the 'client area' of the browser window). If you are unable to find out how to do this, simply set an arbitrary limit for the div's left css-property. For example, when the div's left property exceeds, say, 500 pixels, the direction-reverse logic should operate to change the direction of motion.


Result


let theDiv = null;
let xPos = 0;
let viewportWidth = window.innerWidth;
let goLeft = viewportWidth;
function onLoad() {
theDiv = document.getElementById('obj_1');
setInterval(onTick, 10);
}
function onTick() {
if (xPos < viewportWidth) {
theDiv.style.left = xPos + 'px';
xPos = xPos + 1;
goLeft = viewportWidth;
}
if (xPos == viewportWidth) {
theDiv.style.left = goLeft + 'px';
goLeft = goLeft - 1;
}
if (goLeft < 0) {
goLeft = 0;
xPos = 0;
theDiv.style.left = xPos + 'px';
xPos = xPos + 1;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Session Code</title>
<script src="Animation.js"></script>
<style>
body {
margin: 0;
background-color: lightgray;
}
div {
background-color: crimson;
width: 30px;
height: 30px;
border-radius: 3px;
position: absolute;
top: 100px;
}
</style>
</head>
<body onload="onLoad()">
<div id="obj_1"></div>
</body>
</html>