Cookie Based Expand/Collapse Div Architecture in ASP.Net Website

Introduction:

While working the other day I came across a need for an expand/collapse "div" architecture in an ASP.Net website (please refer to the image below), with expand/collapse state persistence.

 
image1.png

 

To be more responsive I needed to implement it using JavaScript. And to persist the expand/collapse state of the "div", cookies were my best bet.

Let me share this with you.

Solution:
 

First of all please create a website in Visual Studio. On the default page create the "div" architecture.

image2.jpg

The CSS classes and the onclick functions mentioned in div definitions are elaborated in more detail later in this article.

CSS: Add a CSS file to the created solution:

JavaScript: all major functionality is handled by JavaScript.  Please add a Jscript (.Js) file to the solution. Functions and variables are elaborated below:

image4.png

In the above two lines, two variables are defined for matching Ids of divx in the created architecture.

image5.png

The CheckState() function checks whether state cookie exists or not and accordingly make calls to proper functions.

image6.jpg

The above two functions handle saving the current expand/collapse state of "div" elements and retrieval of saved state respectively.

image7.jpg

This function is for toggling expand/collapse image.image8.png

This function is for toggling expand/collapse image.

image9.jpg

ToggleSelection() function is called when expand/collapse image is clicked with the div element's (from where it has been clicked) ID as parameter.

Now everything is in place; run the code and voila!! Expand collapse will work as expected with expand/collapse state information in a cookie. To check if expand/collapse state is being persisted, please refresh the page after changing any/all div states.
 

Hope this will help somebody. You can see it in action in the attached code (zipped).


Similar Articles