Search code examples
javascripthtmlcsspostback

Keep Collapsable Div Open After Postback


I have a panel containing a bunch of these filters. By default they are all collapsed, but when you click the button it expands the div. However, every time there is a postback the div is collapsed. How can I make the current state of the div persist across postbacks?

                <h4 class="contentFilterHeader">Start Date</h4>
                <button type="button" class="btn" data-toggle="collapse" data-target="#startDate">
                <div id="startDate" class="collapse">
                    <label for="from">Before:</label>
                    <div class="form-group">
                        <div class="date">
                            <div class="input-group">
                                <input type="text" class="form-control" id="startPicker" runat="server" name="date" />
                                <span class="input-group-addon><span class="glyphicon glyphicon-calendar"></span></span>
                            </div>
                        </div>
                    </div>

Solution

  • You can add runat=server to the entire #startDate div and set Class to them from code behind after checking isPostBack or better yet append a little javascript code to open it on page ready

    startDate.innerHtml = startDate.innerHtml + "<script> $(document).ready(function(){ $('#startDate').collapse('show') }) </script>";
    

    Assuming you are using c# and bootstrap

    EDIT

    You can use the following code http://codepen.io/jammer99/pen/eZyqEN

    var t,
      //read cookie and determine if any panel was open before
      earlierPanel = readCookie("openpanel")
      //if value is found collapse all earlier panels and then open the last panel
    if (earlierPanel) {
      $('#accordion .panel-collapse').removeClass("in");
      $("#" + earlierPanel).addClass("in")
    }
    //reset the behaviour when user opens another panel
    $('#accordion').on('shown.bs.collapse', function(w) {
      t = w.target;
      createCookie("openpanel", $(t).attr("id"))
    })
    
    // remove cookie value using the following or you can write your code to delete the cookie
    $('#accordion').on('hide.bs.collapse', function(w) {  
      createCookie("openpanel","")
    })
    
    function createCookie(name, value) {
      document.cookie = name + "=" + value + "; path=/";
    }
    
    function readCookie(name) {
      var e = name + "=";
      var a = document.cookie.split(";");
      for (var d = 0; d < a.length; d++) {
        var f = a[d];
        while (f.charAt(0) == " ") {
          f = f.substring(1, f.length)
        }
        if (f.indexOf(e) == 0) {
          return f.substring(e.length, f.length)
        }
      }
      return null
    };