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>
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';
});
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With