loading...

Vanilla JS FadeIn/Out

bmsvieira profile image Bruno Vieira Updated on ・1 min read

It looks like JQuery is slowly starting to be "a thing of the past".. so i recently migrated my project from JQuery to Vanilla.. and the result is quite satisfying.

First, you can be sure that if you made it with JQuery, you will make it with Vanilla aswell, but keep in mind that may required a few more lines of code.

One of the things that i used to use alot with JQuery was FadeIn/FadeOut... now the question was: how to do it in Vanilla?

Well... quite easy actually.
Hope it helps someone.

        // ** FADE OUT FUNCTION **
        function fadeOut(el) {
            el.style.opacity = 1;
            (function fade() {
                if ((el.style.opacity -= .1) < 0) {
                    el.style.display = "none";
                } else {
                    requestAnimationFrame(fade);
                }
            })();
        };

        // ** FADE IN FUNCTION **
        function fadeIn(el, display) {
            el.style.opacity = 0;
            el.style.display = display || "block";
            (function fade() {
                var val = parseFloat(el.style.opacity);
                if (!((val += .1) > 1)) {
                    el.style.opacity = val;
                    requestAnimationFrame(fade);
                }
            })();
        };

It works really well and it gives your project a little personality :P

Posted on by:

bmsvieira profile

Bruno Vieira

@bmsvieira

Web Developer for more than 7 years, PHP, JavaScript, SQL, Node.js

Discussion

markdown guide