Search code examples
javascriptjquerytwitter-bootstrap-3local-storagestringify

How to Modify Bootstrap Collapse with a unique id for open and closed state on page reload


I have built a expanding tree-list using bootstrap collapse.. (Without accordion, which seems to be rare I learnt when trying to google it) The first problem I encountered was that the open/closed position of each item on page reload, wasn't recorded and therefore needs to be saved using local storage. Easy.

However, The subsequent problem is getting each tree-item to act individually and not remembering each other's position. Thus we need to generate a unique ID for open and closed state for each individual item so that they won't open and close together.

UPDATE:

Thanks to SPViradiya for providing this easy solution combining both open, closed and rotating arrow, with little HTML and CSS.

https://jsfiddle.net/SPViradiya/nm6tqxsL/1/

$(document).ready(function () {
    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');
         console.log($( "div[href='#"+item+"']"));
         $( "div[href='#"+item+"']").addClass('rotateOn');
        }
        else
        {
         $( "#"+item).collapse('hide');
         $( "div[href='#"+item+"']").removeClass('rotateOn');
        }
    }
  }
}

$('.expand').click(function() {
    //store the id of the collapsible element
     $(this).toggleClass('rotateOn');
   setTimeout(function(){
    var uniqueid = {};

    $('.expand').each(function(){
       var getID = $(this).attr('href').replace(/#/g,'');
       uniqueid[getID] = $("#"+getID).hasClass('in');
    }); 
    localStorage.setItem('uniqueid', JSON.stringify(uniqueid)); 
   },500);



});

})

Solution

  • 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)); 
    
    
    });