How to use jQuery cookie to remember a trigger class for all URLs of the website and not just a page

StackOverflow https://stackoverflow.com/questions/18124044

  •  23-06-2022
  •  | 
  •  

The following code example is using jQuery cookie to remember the latest trigger class for the side-bar navigation. So it will remember if the side-bar is collapsed or open and keep the same status after refresh or reload.

However this is remembering the latest class for each page separately and not for the whole website. For example if the side-bar collapsed in page1, I need it to be collapsed in page2 and other pages as well until I click for uncollapse. However currently it is saving the side-bar class for each page separately.

I am running the website locally on my local server.

Here is the code in jsFiddle: http://jsfiddle.net/hJAk3/3/

Here is the HTML:

<div id="side-bar">
     Side-bar Menu <br /><br />         
     Page1 <br /><br />        
     Page2    
</div>

<button class="collapse">
    test
</button>

Here is the JS code:

if($.cookie("state") == 1) {
  $('#side-bar').addClass("collap");
} else {
$('#side-bar').removeClass("collap");
}

$(".collapse").click(function() {
    $("#side-bar").toggleClass("collap");
if($("#side-bar").hasClass("collap")) {
    $.cookie("state", 1);
} else {
    $.cookie("state", 0);
}
});
有帮助吗?

解决方案

Have you tried this :

Create expiring cookie, valid across entire site:

$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

For more info go to https://github.com/carhartl/jquery-cookie

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top