Search code examples
javascripthtmlcsssafari

JS fade between pages doesn't work on Safari


I've put a little JavaScript fadeIn/fadeOut transition between pages from my website:

window.transitionToPage = function(href) {
    document.querySelector('body').style.opacity = 0
    setTimeout(function() { 
        window.location.href = href
    }, 750)
}

document.addEventListener('DOMContentLoaded', function(event) {
    document.querySelector('body').style.opacity = 1
})

It simply changes the opacity to create the fade.

It works pretty well except in one case. When I'm on Safari, and click the return button of the browser. The opacity seems to stay at 0 and doesn't show the content. It works when I ⌘R.

Any ideas on how to launch this transition when hitting the return button? Or any other solution? Thanks a lot.


Solution

  • When pressing the back button, the browser returns to the state just before the URL changed.

    If you change your code to reset the opacity just before the navigation, you might be able to return to a visible page, without it affecting the fade effect.

    window.transitionToPage = function(href) {
        document.querySelector('body').style.opacity = 0
        setTimeout(function() { 
            // Reset opacity for back navigation.
            document.querySelector('body').style.opacity = 1
            window.location.href = href
        }, 750)
    }