Start here
span.style.opacity = 0;
You will need to gradually redraw the opacity here.
span.style.opacity = 1;
You will need to use the asynchronous construct ( setTimeout / setInterval / requestAnimationFrame ) to iterate because the synchronous ( while / for / for-in / forEach ) will block the main thread, preventing the browser from actually rendering the element with updated opacity.
function fadeIn(element) { function transition() { if(element.style.opacity < 1) { requestAnimationFrame(transition); element.style.opacity = Number(element.style.opacity) + 0.05; } } transition(); }
Alternatively, if you are happy to use CSS (rather than pure JS), you can do this with classes and transitions.
.out { opacity: 0; transition-duration: 0.5s; } .in { opacity: 1; transition-duration: 0.5s; }
Make sure the element has an out class when it arrives at the DOM, and then when you are ready to put it out, replace it with the in class and the browser will handle the animation for you.
source share