0

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?

Metzed
  • 470
  • 1
  • 8
  • 27
  • That's how javascript works, it starts all over when the page is loaded again. To keep track of things you'll need persistent storage, like a database, local storage or cookies, and you have to create the functionality that keeps track of the users actions yourself. Good luck ! – adeneo Aug 20 '13 at 21:55

2 Answers2

0

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.

benestar
  • 552
  • 4
  • 12
0

This worked for me: Having a cookie to keep the button pressed state, and a cookie to keep track wich button was actually pressed (for more than one button, check also which whas pressed)

var buttonpack;

$(function(){
 if( ($.cookie("ButtonPressedState") == 1) && ($.cookie("buttonCookie")=="buttonpack")) {
   $('#'+$.cookie("buttonpack")).toggleClass("inputbutton:active active");
       } else {
     $(this).siblings().removeClass('inputbutton:active active');
         }

$('.inputbutton').click(function () {
     $(this).toggleClass("inputbutton:active active");
     $(this).siblings().removeClass('inputbutton:active active');
       ButtonId = $(this).attr('id'); 
      if(($('.inputbutton')).hasClass("inputbutton:active active")){
       buttonpack=$(this).attr('id');

       $.cookie("ButtonPressedState", 1, {expires: 1, path:'/'});
       $.cookie("buttonId", buttonpack, {expires: 1, path:'/'}); 
      }else{
       $.cookie("ButtonPressedState", 0, {expires: 1, path:'/'});
       $.cookie("buttonpack", null, {expires: 1, path:'/'});
       buttonpack=null;
        }
     
    });
 });