Search code examples
javascriptcsshtmllocal-storageweb-storage

How to local storage expand/collapse CSS settings


I'm looking for way to use local storage to remember the CSS settings of a expand/collapse element

so for my JavaScript looks like this (which grabs the id and handles the expand/collapse)

function toggleHeight(id, link) {
    var e = document.getElementById(id);

    if(e.style.maxHeight == '450px') {
        e.style.maxHeight = '0px'; 
    } else {
        e.style.maxHeight = '450px';
    }
}

So what I am looking for is something that grabs the div id på clicking a link and stores the changes when clicking and then remembering is when refreshing.


Solution

  • As promised here is my solution:

    <script type="text/javascript">
    function toggleHeight(id, link) {
    var e = document.getElementById(id);
    var height = localStorage.getItem(id);
    
    if(e.style.maxHeight == '450px' || e.style.maxHeight == 'inherit') {
        e.style.maxHeight = '0px'; 
        localStorage.setItem(id,"closed");
    } else {
        e.style.maxHeight = '450px';
        localStorage.setItem(id, "open");
    }
    }
    
      function load() { 
    
    var setting
    var e
    var link
    for (x in localStorage){
        setting = localStorage.getItem(x);
        e = document.getElementById(x);
        link = document.getElementById('forumlink'+x);
    
        if (setting == 'open')
        {
            e.style.maxHeight = '450px';
        }
        else
        {
            e.style.maxHeight = '0px';
        }   
        }
        }
    
    </script>
    

    This stores the state of the div when clicked and sets in to open/closed

    On page load it grabs the stored value and sets the max-height css after the open/closed value..

    Hope some others can make use of this