Question

I'm changing the background of some Links using JavaScript:

$(document).ready(function(){ 
     $("#home").click( function(){ 
        $("body").removeClass("bg2 bg3").addClass("bg1");
});

     $("#link1").click( function(){ 
        $("body").removeClass("bg1 bg3").addClass("bg2");
});

     $("#link2").click( function(){ 
        $("body").removeClass("bg1 bg2").addClass("bg3");
}); 
}); 

Bg1,2,3 are css classes of background (bg images). I prevent refresh button (to save BG) with hash:

   var x = location.hash;
      if (x==="#link1")
      {
         $ ("body").removeClass("bg1 bg3").addClass("bg2");
      }
      else if (x==="#link2")
      {
         $ ("body").removeClass("bg1 bg2").addClass("bg3");
      }
      });

It work but if i click on back button it doesn't change the background to previous link background. Is it possible to fix it except web storage/session storage? With hash or somethink like this?

Was it helpful?

Solution

When you hit the back button of your browser, the page will not reload because you are using the hash, this means to the browser that you want to move to a different anchor.

To proper manipulate the history stack you need to use the freaking awesome History API

To fix your problem you need to intercept the event triggered when your history stack change.

<html>
<head>
    <script type="text/javascript"  src="../lib/jquery.1.9.2.js"></script>
</head>
<body onload="checkHash();">
    testing hash stuff
    <a href="#white">click to change</a>
    <script type="text/javascript">
        console.log('loaded');
        var checkHash = function(){
            if(location.hash==="#black"){
                $('body').css("background-color","black");
            }else if(location.hash==="#white"){
                $('body').css("background-color","white");
            }
        }
            //the event below will be trigger when you hit backbutton or the link
        window.addEventListener("popstate", function(e) {
            console.log('trigger when hit the back button')
            checkHash();
        });

    </script>
</body>
</html>

IE9 FIX

If you need to implement the same behavior on IE9 you must listen the onhashchange, so you can trigger the code to change the background when backbutton was clicked.

<body onhashchange="alert('trigger the background change function')">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top