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

146
Views
How can I animate an accelerating a DOM element with JavaScript?

I am making an application where I need a object to move from point a to point b starting out fast but then slowing down. I want to do this with pure vanilla js and no libraries whatsoever. This is my current code for animating something at a constant speed and I was wondering if it was possible to modify it or something.

let player = document.querySelector('.player');
var id = setInterval(frame, 1);
let counter = 0;
function frame() {
    if (counter == 50) {
        clearInterval(id);
                counter = 0;
        return;
    } else {
        player.style.top = player.offsetTop - 2 + 'px';
        counter++
    }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It would be better & easier to use CSS3 capabilities. For example you define a CSS class that has CSS transition or transform in it.e.g.

.move{
  transform: translateX(300px);
  transition: transform .3s ease-out;
}

then you simply add or remove the class using JavaScript to the DOM element you want for it to take effect. https://jsbin.com/sosuqoyasi/edit?html,css,js,output

In your case you can make the 300px a CSS variable and update it in your javascript before adding the class

if you want to have more control over the CSS in your JS code use the Web Animation API : https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API

about 4 years ago · Juan Pablo Isaza Report

0

I would use a timeout instead of an interval with some recursion like this...

let player = document.getElementById("player")
let a = 0
const b = 500
const playerWidth = 50

animate = () => {
    a += 20
    setTimeout(() => {
        if (a < b - playerWidth) {
            animate()
        }
        player.style.left = a
    }, a)
}

animate()

here is a working example

https://replit.com/@BenjaminKile/MoralRegularTransformations#index.html

about 4 years ago · Juan Pablo Isaza 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!