Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda