Crashtor Crashtor - 1 month ago 16
jQuery Question

Generate unique id for localstorage

I have built a expanding tree-list using bootstrap collapse. My first problem was having the browser remember the open/closed position of each item on page reload, and I went for storing each state in local storage.

This gave me the problem of each tree-item remembering each other's position so when I stored it as "open" and then refreshed - ALL tree's would expand to open state.

I am now trying to figure out how to generate a unique id for each item so that each collapsible tree-item will only remember the position of itself and not all.

But I'm not getting local storage to retrieve the right id for each item.

$(document).ready(function () {
$('.expand').click(function() {
//store the id of the collapsible element
var uniqueid = { 'one': 1, 'two': 2, 'three': 3 };
localStorage.setItem('uniqueid', JSON.stringify(uniqueid)); $(this).attr('href');
});
var collapseItem = localStorage.getItem('uniqueid');
if (collapseItem) {
$(collapseExample).collapse('show')

$('.expand').click(function() {
localStorage.removeItem('uniqueid' );
});

}
})


Here's the HTML

<div class="expand" data-toggle="collapse" href="#collapseExample" >
BUTTON</div>

<div class="collapse" id="collapseExample">
<div class="well">
SUB-TREE
</div>
</div>


JSfiddle
https://jsfiddle.net/g8y4xvf8/26/

Answer

Try below code on document ready

var getUniqueID = localStorage.getItem('uniqueid');
if( typeof getUniqueID == "string" )
{
    var parsedUID = JSON.parse(getUniqueID);
  if( parsedUID != "" && typeof parsedUID == "object" )
  {
    for( item in parsedUID )
    {
        if(parsedUID[item])
         $( "#"+item+).collapse('show');
        else
         $( "#"+item+).collapse('hide');
    }
  }
}

$('.expand').click(function() {
    //store the id of the collapsible element
    var uniqueid = {};
    $('.expand').each(function(){
       var getID = $(this).attr('href').replace(/#/g,'');
       uniqueid[getID] = $(this).hasClass('collapsed');
    }); 
    localStorage.setItem('uniqueid', JSON.stringify(uniqueid)); 


});
Comments