Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delay leaving a page via javascript?

I'm trying to get add a delay of 1000ms before a person leaved the page. I'm using the beforeunload event to start a jquery animation and would like it to finish before the page leaves.

I'm not concerned with older browsers, IE9, latest safari, chrome and FF4 are all i'm interested in.

Edit: Well I was hoping to implement it when just navigating internal pages. Sure I can make all my internal links a javascript call, but I would have preferred a less brute force method.

Also, I'm not stopping people from leaving the page, not even making them wait a huge long time, 1 second for a fade out? Thats no worse than every game I play fading out when I select quit.

Now had I asked how do I prevent a person from leaving a page, then yes all the "don't do it" would have been deserved.

like image 415
Justin808 Avatar asked Mar 31 '11 05:03

Justin808


2 Answers

Firstly, if people want to leave your page, don't put any barriers or difficulties in leaving it. Just let them.

Konerak said it well...

Using a blocking action is acceptable when the user is about to lose data by leaving the page, but using them for animations and gimmicks will quickly annoy your users.

Secondly, you can only prevent automatic closing with a blocking action, such as an alert() or prompt(), which temporary blocks the browser's viewport, waiting for user response.

jsFiddle.

like image 182
alex Avatar answered Sep 28 '22 19:09

alex


Well I was hoping to implement it when just navigating internal pages.

I know it’s four years later now, but I wanted to point out that, within the bounds you’ve described, you can do this.

$(document).on("click", "a", function (e) {// Listen for all link click events on the page (assuming other scripts don’t stop them from bubbling all the way up)
    // Stop the link from being followed.
    e.preventDefault();

    // Grab the link element that was clicked
    var linkClicked = e.target;

    // I'm using setTimeout to just delay things here, but you would do your animation and then call a function like this when it’s done
    window.setTimeout(function () {

        // Simulate navigation
        window.location = linkClicked.href;
    }, 1000);

    return false;
});

It’s still inadvisable:

  • I suspect it would get annoying to users pretty quickly
  • Without additional code, this would prevent users from command/control-clicking to open links in a new tab.
like image 31
Paul D. Waite Avatar answered Sep 28 '22 18:09

Paul D. Waite