A vanilla JS replacement for fadeOut/fadeIn callbacks

Author: Patrick Nappa

During refactoring jquery-console to not contain jQuery, I ended up having to replace .fadeOut(fn) and .fadeIn(fn) a few times, which I can imagine will be useful to others.

Here's a quick snippet for replacing fadeOut.

jQuery equivalent

$("#someelement").fadeOut(function() {
    console.log("element has faded out...");
});

Vanilla JS equivalent

var el = document.querySelector("#someelement");
el.addEventListener('animationend', function(){
    console.log("element has faded out...");
});
el.classList.add("fadeout");

You also need CSS for it:

@keyframes fadeout {
    from {
        opacity: 1;
    }

    to {
        opacity: 0;
    }
}

.fadeout {
    animation-name: fadeout;
    animation-fill-mode: forwards;
}

From the moment that the class is attached the animation starts. animation-fill-mode: forwards is necessary for the element to stay faded out at the end of the animation, as it means the element will take the final result of the animation after it has concluded, by default it may reset to the beginning state of the animation.

fadeIn

fadeIn is exactly the same, but you'll need to add a CSS animation for fading in:

@keyframes fadein {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

.fadein {
    animation-name: fadein;
    animation-fill-mode: forwards;
}

In addition, you'll need to replace this line: el.classList.add("fadeout"); with el.classList.add("fadein").

Closing Remarks

This works for any animation that finishes, so if the animation is infinite, or is a transition rather than an animation, you may have more luck achieving your result by reading this article.


Hello, world!

Author: Patrick Nappa

If you're reading this, my blog must work. Whether or not its held together by no-frills duct tape, well, let's ignore that.

Until next time!