Question

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);
}
Was it helpful?

Solution 2

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.

OTHER TIPS

From MDN:

When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog.

onBeforeUnload is used to prompt a user, not to perform actions (like ajax, animations, or otherwise)

https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload

There's no API to accomplish what you are looking to do. If a user is leaving, the only thing the browser will let you do is prompt them and ask them if they are sure they want to leave. You cannot prevent them (or delay them while still maintaining control of the UI, or anything that uses a JavaScript API) from navigating away from your page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top