Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Reversing a moving object in JS

My task is to create a ball and make it move back and forth across the screen. I have made it move in one direction but am having issues making it go in reverse. Here's what I have thus far:

function moveBall() {
  positionX = positionX + velocity;
  ball.style.left = positionX + 'px';
  let reserve = false
  if (positionX = 20000 + 'px') return;
  !reverse;
}

The if statement only stops the ball at a certain point but doesn't make it turn around.

I'm sure it's something really simple that I'm just overlooking, especially at this point because I've been googling the hell out of this, so if anyone can give a noobie a hand that would be much appreciated!!

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

Try this code, which uses a variable reverseNum to track whether or not the velocity should be negated.

HTML:

<body></body>

JS:

document.body.onload=function(){
ball=document.createElement("DIV");
ball.style.width="100px"; //Ball radius
ball.style.height="100px"; //Ball radius
ball.style.borderRadius="100%";
ball.style.backgroundColor="red";
ball.style.position="absolute";
document.body.appendChild(ball);
setInterval(function(){moveBall()},100)}
var positionX=0;
var velocity=100;
var reverseNum=1;//1 if should reverse is false, -1 if should reverse is true
function moveBall() {
  positionX = positionX + velocity*reverseNum;
  ball.style.left = positionX + 'px';
if(positionX>20000){
reverseNum=-1;
}
}
about 4 years ago · Santiago Gelvez Report

0

positionX = positionX + velocity;

So by adding velocity to positionX makes it go forth, then reverse of it, which is minus velocity will make it come back.

And use if condition to separate the forth and back.

for eg.

function moveBall() {
  if (positionX = 20000 + 'px'){
    positionX -= velocity; //same as positionX = positionX - velocity;
  }else{
    positionX += velocity;
  ball.style.left = positionX + 'px';
  let reserve = false; // not sure what you trying to do with this;
  !reverse;  // and this
}

and if you want to get current moving status by the reverse , just set false when minus and true and plus.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!