Search code examples
javascripthtmldombrowser-history

Adding Browser History and Navigation To JavaScript DOM Page Change Function


I am using JavaScript to change the pages of my website, but I am running into the issue where I can't use browser navigation to go back or forwards through the history once I have changed pages.

I have tried adding a /#pagename to the URL for each page, and a few other things, but I can't seem to find something that works. I need to be able to make sure that the browser is saving the history of the page changes I make, so it can navigate those pages with the forward and back buttons.

// Change Page Function

function ChangeContent (page) {

var pages={"homepage":{title: "homepage"},"servicespage":{title: "servicespage"}};


//Show home page
for(var homepage in pages) {

    if(page!==homepage) {

        document.getElementById(homepage).style.display='none';
    }

    else {

        document.getElementById(homepage).style.display='block';
        window.scrollTo(0,0);
    }
}

//Show services page
for(var servicespage in pages) {

    if(page!==servicespage) {

        document.getElementById(servicespage).style.display='none';
    }

    else {

        document.getElementById(servicespage).style.display='block';
        window.scrollTo(0,0);
    }
}
}

Solution

  • You should look at window.history.pushState to add history entries and window.onpopstate to react to the user travelling "backward" through the entries you've added.

    When you want to "change" pages, make a call like:

    window.history.pushState( stateData, title, url );
    

    where...

    • stateData is some object containing data you define
    • title is a string name for the new state
    • url is the string to which the browser's url should be changed

    For example, if you want to change to "servicespage" and make the url change to "/#services":

    window.history.pushState( { title: "Services" }, "servicespage", "/#services" );
    

    Note that you still have to manipulate the DOM at this point.

    Then, if you want to react to the user going backward through history:

    window.onpopstate = function( event ) {
      var data = event.state;
    
      // data references the first argument of 'pushState'
      // do whatever showing or hiding of <div>s here
    };