javascripthtmlcss

How can I create transitions between different webpages on my website?


The question is as the title states. I'm attempting to create transitions between pages in order to spruce up my website. Particularly, I'd like to be able to have the page content slide off-screen (in any cardinal direction), load the next page, and have that page's content slide on-screen (from any direction, though I'd want it to be the opposite of the sliding off-screen animation).

I currently have code for fading pages in and out (credit to maxpaj) but this comes with a couple problems. Firstly, I'd rather have it be that the page slides rather than fades (if I can), and secondly, going back a page makes the Javascript that fades in the page content fail to work. Ideally, I'd be able to find a solution that fixes both these problems.

I've scoured as many results as I can but all of the documentation on page transitions I can find either only deals with fading the page (which is code & principles which I haven't been able to adapt to accommodate sliding rather than fading, despite my best efforts), doesn't actually provide the mechanics behind the code (i.e. paywalls or only showing recorded demos rather than live ones), or doesn't work with Neocities (i.e. View Transition API, which Neocities does not recognize to my knowledge).

I'm currently using Neocities with limited HTML, CSS, and JS knowledge. I'm not worried about using JS (though I have no experience with JQuery) but do keep in mind that my remedial knowledge will mean that I will probably not get many coding principles at first.


Solution

  • I turns out that when you click your back button, most modern browsers don’t trigger a full reload. They instead may use the back/forward cache (bfcache), which restores the page from memory rather than re-executing your script from scratch.

    You can try the pageshow event

    Can you try this modified version of this script to see if it works for you

    window.transitionToPage = function(href) {
        document.querySelector('body').style.opacity = 0
        setTimeout(function() { 
            window.location.href = href
        }, 500)
    };
    
    const showBody = () => document.querySelector('body').style.opacity = 1;
    
    // On first load
    document.addEventListener('DOMContentLoaded', showBody);
    
    // On bfcache restore (back/forward navigation)
    window.addEventListener('pageshow', (event) => {
      if (event.persisted) showBody();
    });