Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda