Search code examples
javascriptjquerycsssession-statepage-refresh

Store div status on page reload


I have multiple divs in one html page under common wrapper class. I am using hide and show method on clicking next and previous option.

What I am trying to achieve: On page reload/refresh, the div which is showing currently should show after page reload.

So in short if you reload/refresh from pink screen, it should show same pink screen after page reload.

What I tried: I am storing the display properties (none or block) is local storage and on page reload trying to give same properties to divs again. Most of the responses and solution I checked in Stack overflow is regarding opening the same tab when refresh. but my case is what in same tab I have multiple div and I want to open from the same state which it was earlier.

Logic I used:

$(window).on('load', function(){
  var disp = localStorage.getItem("disp");
  var ustatus = JSON.parse(disp);
  $(".chk").text(ustatus);
  for (var x=ustatus; x<ustatus.length; x++){
    $(".pg"+x).css("display", ustatus[x]);
  }
});

This is fiddle link I tried:

Page reload demo JS Fiddle link


Solution

  • You don't really need the on class:

    $(window).on('load', function(){
      var disp = localStorage.getItem("disp");
      var ustatus = JSON.parse(disp);
      $(".chk").text(ustatus);
      for (var x=0; x<ustatus.length; x++){
        $(".pg"+(x+1)).toggleClass("off", ustatus[x]);
      }
    });
    
    $(".next").on("click", function(){
      $(this).parent().addClass("off");
      $(this).parent().next().removeClass("off");
    });
    
    $(".prev").on("click", function(){
      $(this).parent().addClass("off");
      $(this).parent().prev().removeClass("off");
    });
    
    $(window).on('beforeunload', function(){
      var display = $(".clr").map(function(){
        return $(this).hasClass("off");
      }).get();
      localStorage.setItem("disp", JSON.stringify(display));
    });
    

    Fiddle

    note: you can't use $(window).on('load', ...) in a fiddle - the JS in the editor is run on load

    EDIT: you might also want to validate ustatus before applying it, something like

    if (Array.isArray(ustatus) && ustatus.filter(x => x === true).length === 1) {
      for (var x=0; x<ustatus.length; x++){
        $(".pg"+(x+1)).toggleClass("off", ustatus[x]);
      }
    }