I would like to have an animation effect which starts when people leave a page.
I use this currently:
window.onbeforeunload = function (){
alert
I am working with onbeforeunload and What I was able to figure out is:
So your code will be working as long as the event handler runs. This means that timer functions are not usable. They just add to the execution queue, so anything they would do is being queued after the end of currently running handler, which is after the last point in time you were guaranteed your code is still running.
So there is only one way to stop the browser from unloading before the animation finishes:
beforeunload
handler Oh, and yes, this is a nastiest hack of all, but I was able to find a way to stop the browser from unloading the page, right?
I would appreciate comments with ideas on what to put in the loop. I am taking some options into account:
Any ideas?
Jorrebor, If your trying to have this animation fire when they leave your site or close the browser it will not work as intended. However, you can create this animation while the user travels within your site by removing the 'href' property of your links and creating animations that have a callback function that set the window.location property. Something like:
document.getElementById('home').onclick(function(){
yourAnimationFunction(function(){
window.location="example.com";
});
});
alot of work and wont be seo friendly however
onbeforeunload
can delay the page unload in only one case: When a return
statement with a defined value is returned. In this case, the user gets a confirmation dialog, which offers the user an option to not leave the page.
Your desired result cannot be forced in any way. Your animation will run until the browser starts loading the next page:
[User] Navigates away to http://other.website/
[Your page] Fires `beforeunload` event
[Your page] `unload` event fires
[Browser] Received response from http://other.website/
[Browser] Leaves your page
[Browser] Starts showing content from http://other.website/
Assuming jQuery for the sake of brevity:
$('nav a').click(function (e) {
//ignore any "modified" click that usually doesn't open in the current window
if (e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.isDefaultPrevented()) {
return;
}
//where you going here?
var place = this.href;
//you're not going anywhere, buddy
e.preventDefault();
//watch me dance, first
$('.animate-me').fadeOut(1000, function afterAnimation () {
//you're free to go!
document.location = place;
});
});
Basically, you don't use onbeforeunload
. One advantage is that you can keep the user as long as you want, one disadvantage is that the user won't see an animation when using a link outside nav
(but you can just change the selector)
Obviously keep the animation fast, like suddenlyoslo.com do.