C# Tutorial: Saving the State of a Bootstrap Collapsible Panel Using JavaScript and Cookies

In this tutorial, I will show you how you can cause a browser to remember the state (open or closed) of a Bootstrap collapsible panel using C#, JavaScript, and cookies.  First, open a new project in Visual Studio by navigating to File -> New -> Project… (or hit Ctrl+Shift+N).

Visual Studio New Project

Next, I will select Templates -> Visual C# -> Web -> ASP.NET Empty Web Application and name the project CollapsiblePanelDemo.  I will also check the option to Create a directory for solution and hit the OK button to continue.

CollapsiblePanelDemo Project

Now, I will add an ASP.NET Web Form page to my project by right clicking the project name and selecting Add -> Web Form.  In the Specify Name of Item window, I will type in Default and then click on the OK button.

Add Web Form

In the Source view mode, I will add the following lines of code.  Place this in the HTML header section:

<title>CollapsiblePanelDemo</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" type="text/css" />

Source View

And place this code right above the </body> tag of the page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

These are the Bootstrap libraries which will allow you to create a collapsible panel using relative simple markup.  Let’s start by placing a button on the page.  Place this piece of code in between the <form> tags:

<div class="container">
<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#Panel1" id="panel1State" onclick="setCookie('Panel1')">Panel 1</button>
</div>

Let’s add another button by placing this piece of code underneath the first button:

<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#Panel2" id="panel2State" onclick="setCookie('Panel2')">Panel 2</button>

Add a line break and create the panels by adding this code right after the second button:

<br />
<div id="Panel1" class="collapse">This is Panel 1.</div>
<div id="Panel2" class="collapse">This is Panel 2.</div>

Here’s a quick breakdown of how the panels work.  The panels are created using the <div> tag and to differentiate the panels, we use the id attribute.  The data-target attribute in the <button> tag references the id value of the panel it’s supposed to control.  The onclick attribute in the <button> tag will be used later to call a JavaScript function which will place a cookie on the computer for the duration of the session to remember the last “state” of the panel.  Go ahead and hit F5 at this point to compile your application so that you can test out how the buttons currently work.

Test Run 1

Now, let’s write some JavaScript that will help your application remember the last state (open or closed) of the panel.  In the Solution Explorer window and under Solution, right click on “CollapsiblePanelDemo” and navigate to Add -> JavaScript file.  Name the file panelState and click on the OK button.

Add JavaScript File

Enter the following code in the file and save it:

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1);
    if (c.indexOf(name) != -1) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function setCookie(sectionName) {
  var lastState = getCookie(sectionName);
  if (lastState == "" || lastState == "off") {
    document.cookie = sectionName + "=on";
  }
  else {
    document.cookie = sectionName + "=off";
  }
}

function setState() {
  if (getCookie("Panel1") == "" || getCookie("Panel1") == "off") {
    document.getElementById("Panel1").className = "collapse";
  }
  else {
    document.getElementById("Panel1").className = "collapse in";
  }

  if (getCookie("Panel2") == "" || getCookie("Panel2") == "off") {
    document.getElementById("Panel2").className = "collapse";
  }
  else {
    document.getElementById("Panel2").className = "collapse in";
  }
}

One function gets the cookie (i.e. reads the data), another sets it, and the last function is used to determine the last state the panel was in (i.e. open or closed).  Let’s add a reference to this JavaScript file by adding this markup right above the </body> tag of our page:

<script src="panelState.js"></script>

We also add an onload event in the <body> tag to call the setState() function:

<body onload="setState()">

Now, let’s add a Submit button that will initiate a post-back.  Drag an ASP.NET button control on to the form and place it right under the second button.  Change the ID to “submitButton” and Text to “Submit“.  I’ll also add this attribute (CssClass=”btn btn-primary”) to the button control for styling.  And that’s it.  Hit F5 to compile and run your application to test it.  You’ll notice that when you click on a Panel button and then click on the Submit button or if you reload the page that the browser will remember the last state (open or closed) that the panel was in and keep it that way.  This behavior will be in effect for both regular load and post-back operations until the browser is closed.  If you’d like to review the code, you can download the entire Visual Studio project using the link below:

CollapsiblePanelDemo