Skip to content

Instantly share code, notes, and snippets.

@fregante
Created July 20, 2012 01:36
Show Gist options
  • Save fregante/3148116 to your computer and use it in GitHub Desktop.
Save fregante/3148116 to your computer and use it in GitHub Desktop.
Add class when leaving page
//make sure downloads open in another page with target="_blank"
//"beforeunload" is fired any time a link is clicked.
//If the link points to a file to download, the user won't be actually leaving the page, but beforeunload will still have fired.
(function () {
var unload = {};
unload.init = function () {
//cache html element
unload.$html = $(document.documentElement);
//attach event
$(window).on('beforeunload', unload.unloading);
}
unload.unloading = function (e) {
unload.$html.addClass('unloading');
//set fallback
setTimeout(unload.failed, 3000);
}
//useful if the user comes back, the loading fails, or it takes way too long
unload.failed = function () {
unload.$html.removeClass('unloading');
}
//set this whole thing up on DOMready
$(unload.init);
return unload;
})();
.unloading .element-to-animate {
animation: fade-out 1s;
}
@mindfullsilence
Copy link

This is great, thanks!

@Jekeru
Copy link

Jekeru commented Jan 18, 2021

So nice, thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment