Modern fade using JS
https://github.com/julienetie/fadeto/blob/master/fadeto.js
by Julien Etienne
CSS
div{
width: 200px;
height: 200px;
background: red;
}
JavaScript
const precision = 3
const assumedFps = (1 / 60).toPrecision(precision);
const fadeTo = (el, rate, fadeToVal, display) => {
const raf = window.requestAnimationFrame
const style = el.style
style.opacity = window.getComputedStyle(el).opacity //Set opacity to computed value
const fade = () => {
// Disclaimer: Not a representation of duration, but assumes repaints at assumedFps
const increments = assumedFps / rate
//Fade out then set display
if (style.opacity > fadeToVal) {
if ((style.opacity -= increments) < fadeToVal) {
if (style.opacity <= 0.01) (el.style.display = display)
return
}
raf(fade)
return
}
//Fade in then set display
let val = parseFloat(el.style.opacity)
if (((val += increments) < fadeToVal)) {
style.opacity = val
if (style.opacity > 0.99) style.display = display
raf(fade)
}
}
fade()
}
const div = document.querySelector('div')
fadeTo(div,1, 0)