Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate element using Javascript vanilla

How can I animate an element with Javascript vanilla? Similar with jquery. Example:

$( "button.continue" ).animate({left: "100px", top: "200px"}, 5000);

Where we pass the attribute, the desired value and the time.

In my case I need the left and top position to animate and slide.

Solution

I've done as @IceMetalPunk sugested and added the animation by css only when I need to animate.

document.getElementById("animate").addEventListener("click", function(){
  let e = document.getElementById('elementToAnimate');

  e.classList.add("animate");
  setTimeout(()=> e.classList.remove("animate"), 500);

  e.style.top = Math.floor(Math.random() * window.innerHeight) + 'px';
  e.style.left = Math.floor(Math.random() * window.innerWidth) + 'px';
});

document.getElementById("dontAnimate").addEventListener("click", function(){
  let e = document.getElementById('elementToAnimate');

  e.style.top = Math.floor(Math.random() * window.innerHeight) + 'px';
  e.style.left = Math.floor(Math.random() * window.innerWidth) + 'px';
});
#elementToAnimate {
  width: 20px;
  height: 20px;
  background: red;
  position: absolute;
  top: 0;
  left: 0;
}

#elementToAnimate.animate {
  transition: left 500ms ease-in-out, top 500ms ease-in-out;
}
<div id="elementToAnimate"></div>

<button id="animate">Animate</button>
<button id="dontAnimate">Dont Animate</button>
like image 901
Diogo Peres Avatar asked Oct 18 '25 15:10

Diogo Peres


2 Answers

Try using CSS transitions. In CSS, do something like this:

button.continue {
  transition: 5s;
}

Then in JS, you can just set the left/top values:

document.querySelectorAll('button.continue').forEach(button => {
  button.style.left = '100px';
  button.style.top = '200px';
});
like image 167
IceMetalPunk Avatar answered Oct 20 '25 04:10

IceMetalPunk


Tested in Firefox.

document
   .querySelector(".text.thank-you")
   .animate({ opacity: [0, 1] }, { duration: 5000, iterations: 1, easing: "ease-out" })
   .onfinish = (e) => {
        e.target.effect.target.style.opacity = 1;
   };
like image 45
N-ate Avatar answered Oct 20 '25 03:10

N-ate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!