I am facing an issue with my code. I have a div with the id "ball" that is initially moving towards the top and left. However, when it reaches the top of the wrapper block (with the id "field"), the direction of the ball should change. Unfortunately, the direction changes incorrectly. Below is my code. Please bear with me as I am new to coding and seeking help to resolve this issue.
var ball = document.getElementById('ball');
var timer = setInterval(function ()
{
var posTop = ball.offsetTop;
var posLeft = ball.offsetLeft;
var ballPositionX = parseFloat(window.getComputedStyle(ball).left);
var ballPositionY = parseFloat(window.getComputedStyle(ball).top);
ball.style.top = --posTop + 'px';
ball.style.left = ++posLeft + 'px';
if (ballPositionX <= 0)
{
ball.style.top = --posTop + 'px';
}
if (ballPositionX <= 550)
{
ball.style.top = ++posTop + 'px';
}
if (ballPositionY <= 0)
{
ball.style.left = ++posLeft + 'px';
}
if (ballPositionY >= 1000)
{
ball.style.left = --posLeft + 'px';
}
}, 10);
HTML:
<div class="field" id="field">
<div id="here"></div>
<div class="ball" id="ball"></div>
<div class="desk" id="desk"></div>
</div>
CSS:
* {
margin: 0;
padding: 0;
}
.field {
margin: 15px auto;
width: 1000px;
height: 650px;
border: 1px solid #000;
background: aliceblue;
position: relative;
overflow: hidden;
}
.ball {
width: 50px;
height: 50px;
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
background: green;
-webkit-border: 5px double silver;
-moz-border: 5px double silver;
-ms-border: 5px double silver;
-o-border: 5px double silver;
border: 5px double silver;
position: absolute;
top: 550px;
left: 0;
}
.desk {
width: 200px;
height: 25px;
background: darkblue;
-webkit-border: 3px double silver;
-moz-border: 3px double silver;
-ms-border: 3px double silver;
-o-border: 3px double silver;
border: 3px double silver;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
position: absolute;
top: 610px;
left: 10px;
}
.blocks {
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 30px;
background: brown;
text-align: center;
color: lightcoral;
}