Using the JS beforeunload event for smooth page transitions

It’s pretty simple but a thing that took me a while to realize: One big problem with normal pages compared to webapps are the hard transitions from one page to another. Normal pages reload a new page on every click on a link, resulting in page elements instantly disappearing and appearing.

Fading stuff in is pretty common on the web nowadays. Fading stuff out when someone leaves the page isn’t. But it’s pretty cool: Fade in the content on your page on load, and fade out once the user leaves the page (mostly by clicking on a link or going back in history).

The JS beforeunload event

This event is supposed to be used to check if the user needs to confirm leaving the page, e.g. if he filled out a form and would lose his changes without pressing a button. But one can also use it like any other event, in this case to remove a class from specific elements to trigger a fadeout.

Let’s start with some CSS:

.mdl-card {
    pointer:default;
    pointer-events:none;
    transition: opacity 0.125s linear;
    opacity:0;
}
.mdl-card.loaded {
    pointer:initial;
    pointer-events:initial;
    opacity:1;
}

I’m using MDL for the design of this blog, and MDL cards as containers for my content. Per default (when they aren’t loaded), they and their children shouldn’t be clickable. This mainly is about links, because I don’t want invisible (opacity:0) links to be clickable. I also set up the transition.

Once they’re loaded, they fade into full opacity. I also reset the pointer and pointer-events to their defaults, to make things clickable again.

Here’s the JS:

//Smooth page transitions for mdl-cards
var delayFactor = 150;
$(function() {
    $(".mdl-card").each(function(index) {
        var that = $(this);
        var delay = delayFactor * (index + 1);
        setTimeout(function() {
            that.addClass("loaded");
        },delay);
    });
});
$(window).on('beforeunload', function(){
    $(".mdl-card").removeClass("loaded");
});

I’m using jQuery here. Once the page is loaded, each card is getting the “loaded” class, resulting them in fading in.

The beforeunload part is the fun part: I just setup the event to remove the loaded class when the user leaves the page, et voil√†, it fades out again. You can try it by clicking the “next” button on the top to get to the next post.

All in all a small neat trick that results in a smoother user experience. Tested on Firefox and Chrome.

Note: This post was written before switching over to wordpress, it’s not used here anymore.