Search code examples
javascriptjqueryhtmlsinglepage

history.pushtState / back button / Navigation in a single page app


I'm building a small single page app with a navigation. the pages are position in div-container which are display by clicking on a link. The code for the page changig

        // show the given page, hide the rest
        function show(elementID) {
            history.pushState({ 
                plate_id: 1, 
                plate: elementID 
            }, null, elementID);
            goTo(elementID);
        }
        function goTo(elementID) {
            var ele = document.getElementById(elementID);
            if (!ele) {
                console.log("fail");
                return;
            }
            // get all pages, loop through them and hide them
            var pages = document.getElementsByClassName('page');

            for(var i = 0; i < pages.length; i++) {
                pages[i].style.display = 'none';
            }
            // then show the requested page
            ele.style.display = 'block';
        }
        window.onpopstate = function (event) {  
              var content = "";
              if(event.state) {
                content = event.state.plate;
              }
              if (content != '') goTo(content);
        }

the links looks like

<a href="#" onclick="show('Page_1');" id="1">page 1</a>

and the divs

<div id="Page_1" class="page" style="">

now when i'm using a link the url changes to .../Page_1# or .../Page_2# and the page is display directly. Now if i use a back button (own or browser doesn't matter) some magic happens which i don't understand.

for example

  1. clicking on first link -> go to ../Page_1# (directly, everythinks fine)
  2. clicking on secound link -> go to ../Page_2# (directly, everythinks fine)
  3. using back button -> go to ../Page_2 (without # and nothing happens but should go to Page_1???!!)
  4. using back button again -> go to ../Page_1# (nothing happen)
  5. using back button again -> go to ../Page_1 (page 1 is loading)

i don't understand why the thinks in step 3 and 4 happens! it will be nice if someone could help me


Solution

  • Maybe you want your link's onclick to be: onclick="show('Page_1'); return false;" or onclick="return show('Page_1');" and your show function to finish with return false;.

    By returning false, the browser won't actually follow the href="#" but just execute your JavaScript instead.