Pure JS equivalent of jQuery .animate()
What is the equivalent of the following jQuery animate in pure JavaScript?
function animate(element, position, speed) {
$(element).animate({
"top": position
}, speed);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can acheive complex animations with pure javascript by using setTimeout
and setInterval
methods.
Please check here.
Here is the key part of moving an element:
function move(elem) {
var left = 0
function frame() {
left++ // update parameters
elem.style.left = left + 'px' // show frame
if (left == 100) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 10) // draw every 10ms
}
This version uses vanilla javascript .animate() function, which is better or more performant
than requestAnimation frame. & it is also the proper alternative to JQuerys .animate().
you can play around with the iterations, timing functions & fill method aswell as daisy chain it with other animations
document.getElementById("Elem");
Elem.style.position = "absolute";
Elem.animate({
top: ['8px', '280px']
},{ duration: 1760, // number in ms [this would be equiv of your speed].
easing: 'ease-in-out',
iterations: 1, // infinity or a number.
// fill: ''
});
I believe the setTimeout & setInterval functions both use the unsafe eval() function under the hood, but not 100% sure about that, just remember reading an article about it...
Don't Quote me on that! just research it,
but the code I wrote out has been tested to be working..
hope this helps someone...