aqyk7a
Last Updated: February 25, 2016
·
24K
· codesbyaxel
Axel

Fade out page when clicking links

Have you seen websites where the whole page is faded out when you are clicking on links? To make it happen, simply use this code:

/*! Fades out the whole page when clicking links */
$('a').click(function(e) {
e.preventDefault();
newLocation = this.href;
$('body').fadeOut('slow', newpage);
});
function newpage() {
window.location = newLocation;
}

When page is fade out, it can be handy to fade in the new page:

$(document).ready(function(){

/*! Fades in whole page on load */
$('body').css('display', 'none');
$('body').fadeIn(500);

}); 

There´s only one problem: When you are clicking the back-button in your browser, you will come to a page that already is faded out. This is because the browser remembers the "fading out", and it doesn't seem to forget. To avoid this, use this code:

/*! Reloads page on every visit */
function Reload() {
try {
var headElement = document.getElementsByTagName("head")[0];
if (headElement && headElement.innerHTML)
headElement.innerHTML += "<meta http-equiv=\"refresh\" content=\"1\">";
}
catch (e) {}
}

The code above does not work in mobile safari. To force mobile safari to reload the page one time, simply add these lines of code:

/*! Reloads on every visit in mobile safari */
if ((/iphone|ipod|ipad.*os 5/gi).test(navigator.appVersion)) {
window.onpageshow = function(evt) {
if (evt.persisted) {
document.body.style.display = "none";
location.reload();
}
};
}
Say Thanks
Respond

4 Responses
Add your response

1886
over 1 year ago ·
3797
7abc37c95590b1b29400e0bddfff9156

I don't want to be a party pooper, but I'm really not sure this is a good idea.

It needlessly slows down page load speed (fairly significantly) and deviates from a browser's standard behaviour, neither of which are a great idea from a usability perspective.

The delay isn't just caused by the timeout; you're waiting for the DOM ready event before you start fading it in. Having said that, even if you changed the code so that you started the fade as soon as jQuery itself was loaded, I wouldn't be a fan.

over 1 year ago ·
4119
Avatar

Yeah I'm with @gma. I'm pretty sure what you really should be doing if you want to make page transitions pretty is not actually do page transitions at all. The History API is for exactly this purpose.

Something like (but not exactly - this is untested):

a.onclick = function(e) {
    e.preventDefault();
    fadeOut().then(function() {
        history.pushState(null, null, a.href);
        load(a.href).then(fadeIn);
    });
};
window.onpopstate = function() {
    fadeOut.then(loadContent).then(fadeIn);
}
over 1 year ago ·
22770
Ur56qjbz normal

i have a problem whit the lightbox :/

over 1 year ago ·