Search code examples
javascriptjqueryeventsanimationonbeforeunload

How to wait until jquery animation is finished using the onbeforeunload event?


It looks like a basic problem, but I simply can not solve this. I am using an animation to smooth the navigation between pages. The window.onbeforeunload event looks good to fire the animation, but jquery do the animation on a new thread. Is there any way to wait until the animation is finished? I tried using the delay() and setTimeout() jquery functions but they obviously not stopped the function. When I add a loop at the end to wait, the window is not refreshing so the animation not even shown.

My code (jsfiddle):

window.onbeforeunload = function (e) {
    $('#loader-sheet').fadeIn(500);
}

Solution

  • You cannot prevent the page from changing - you can only present some text as confirmation (e.g. "You have an unsaved draft, are you sure you would like to leave?").

    This is by design - imagine if every annoying ad popup was allowed to prevent you from exiting the page by entering a 200-second animation.

    However, you might still be able to do something, depending on exactly why the page is changing. For instance, if they are clicking a link on your page (not using back/forward buttons), then you could override the click handler for each of those links, like:

    $('a[href]').on('click', function () {
        if (/* link would change page */) {
            performPageTransition(this.getAttribute('href'));
            return false;
        }
    });
    
    function performPageTransition(newUrl) {
        $('#loaderSheet').fadeIn(500, function () {
            // Animation complete - move to new URL
            window.location = newUrl;
        });
    }
    

    So instead of following the link instantly, you intercept the click event, and then move the page manually yourself later.

    However, I would also consider whether it's possible to load the new page content via AJAX.