Question

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?

Was it helpful?

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.

OTHER TIPS

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;
								}
					
				});
	});

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top