0

I have this piece of code which works great but, I would like the div to remain open if clicked on when the page is refreshed. ex. the user views a link and then returns to the previous page. The link is an image and the page(div) is a menu of images.

<div id="block1-1">
    <a name="works"></a>
    <a href="#block1-1" onclick="toggle_visibility('block1-1');"><h2>works</h2></a>
</div>

<script type="text/javascript">

   function toggle_visibility(id){
       var e = document.getElementById(id);

       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
   }

</script>
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 2
    Why the jQuery tag? Also, if you want to persist changes on a reload, you need to store a variable somewhere. A cookie, a database, localstorage, etc. – j08691 Apr 28 '14 at 17:36
  • You can use anchor links. Your problem is similar to [linking to tabbed content](http://stackoverflow.com/questions/12964070/). The difference is if you want to support a use case where the surfer opens a div, closes the browser and reopens it. In this use case you have to use a cookie, or a database or localstorage. – surfmuggle Apr 28 '14 at 17:44
  • ok,I believe a cookie would do the trick. Being this is a website it could remember the last state. What would the code look like? I am new to javascript and am struggling a bit. Thanks – user3582339 Apr 28 '14 at 18:04
  • There are so many jquery plugin to save data locally in browser. You can try [jStorage](http://www.jstorage.info/) . jStorage supports all major browsers. – Hannan Hossain Apr 28 '14 at 18:23

2 Answers2

3

Local Storage is probably the simplest solution (only works on some browsers).

Modify your function to include the local storage code:

function toggle_visibility(id) {
    var e = document.getElementById(id);
    if(e.style.display == 'block'){
      e.style.display = 'none';
      localStorage.setItem("show", false);
    }
    else{
      e.style.display = 'block';
      localStorage.setItem("show", true);
      localStorage.setItem("id", e);
    }
    };

Then you'd need to incorporate this:

window.onload=function(){
  if(localStorage.getItem("show")){
    var e = localStorage.getItem("id");
    e = document.getElementById("e");
    e.style.display = 'block';
  }
}
jonode
  • 797
  • 4
  • 15
0

You have to give display style for the div

<div id="block1-1" style="display:block;">
Vishnuraj V
  • 2,819
  • 3
  • 19
  • 23