views:

523

answers:

2

Is there a way to perform a jQuery animation before a user navigates away from a page by clicking on a link, or clicking the back/forward buttons.

It seems like doing the animation in response to an unload event would be sure to cover all the conditions under which a user may leave a page.

However, the new page is loaded before the animation can complete. I could do a busy wait, but that isn't very elegant.

Alternatively, I could intercept clicks on anchors. But that doesn't account for back/forward clicks and possibly other conditions under which user would navigate away from a page.

Yes, I understand that this type of behavior is frowned upon because it leaves the user waiting. However, I am attempting to do this in a very particular situation in which I believe the pros outweigh the cons.

+1  A: 

How fast a user switches web pages using his/her browser is not under your control, but only features within your page.

With the new jQuery 1.3 live() event listener, you can add a listener to all anchors as you proposed, even for all new anchors created after you declare the listener:

$("a").live("click", function(){
  var href = $(this).attr("href");

  var animDuration = 1000;

  // Do animation here; duration = animDuration.

  setTimeout(function () {
    window.location = href;
  }, animDuration);

  return false; // prevent user navigation away until animation's finished
});
Seb
great idea... but offcours letting the user wait is maybe not a good idea, depends on how you're using it
Sander Versluys
Yeah, I know it's not a good idea... but that's what he's asking for: to leave the user waiting before the animation completes :)
Seb
A: 

You'd just need to subscribe a listener to the Document's onbeforeunload event, which is fired when a user leaves a page.

onbeforeunload blocks page navigation until your code returns a Boolean (true to navigate, false to annoyingly block navigation), so you'd just need your animation code to ultimately raise a Boolean when it's complete.

No need to monitor links at all.

ajm
Gave it a try... I don't think that what you describe is the actual behavior of onbeforeunload, at least in Firefox and Safari. The return value seems to be what is displayed as the message in the popup window.
David