i have a ball starting at the upper left corner of a box and when you click on the button then it moves to go to the lower right corner. it stops when it reaches 350px
i want it to go up to the upper right corner after it reaches the lower right corner. but if i copy paste the IfElse statement then the If(pos=350) would run that code right away instead of doing the movement at Else
does that make sense
function animation() {
let id = null;
const ball = document.getElementById("ball");
let pos = 0;
id = setInterval(movement, 5);
function movement() {
if (pos == 350) {
clearInterval(id);
ball.style.background = "green";
} else {
ball.style.background = "red";
pos++;
ball.style.top = pos + "px";
ball.style.left = pos + "px";
}
}
}
#box {
width: 400px;
height: 400px;
margin-top: 20px;
position: relative;
background: yellow;
}
#ball {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
border-radius: 100%;
}
<button onclick="animation()">Click Here</button>
<div id ="box">
<div id ="ball"></div>
</div>
You need to sign in to view this answers
Leave feedback about this