Search code examples
jqueryback-buttontoggleclass

How Can I Keep Class Applied Using toggleClass() when Using Browser's Back Button?


I'm using the jQuery toggleClass to add a class to a DIV when a button is clicked. When the class is added, the DIV is expanded to show all content in the DIV with height:auto;.

My problem arises when I click on a link that takes me to another page, and then hit the browser back button. When I return to the original page the class is no longer applied. Is there a way to keep that class applied throughout the person's visit, even if they visit another page and then hit the back button?


Solution

  • Yes, you can store the toggle state in a cookie. For example there is a jquery plugin calles jquery cookie: https://github.com/carhartl/jquery-cookie After the page has been loaded, you can add or remove the class as it is stated in the cookie.