javascriptjqueryjquery-cookie

Save Javascript toggle state with cookie


I would like to save the state of site-header display. How i can save it with Jquery Cookie?

(function ($) {
// The initial load event will try and pull the cookie to see if the toggle is "open"
var openToggle = getCookie("show") || false;
if ( openToggle )
    div.style.display = "block";
else
    div.style.display = "none";
if ( window.location.pathname == '/' ){
    // Index (home) page
    div.style.display = "block";
}
// The click handler will decide whether the toggle should "show"/"hide" and set the cookie.
$('#Togglesite-header').click(function() {
    var closed = $("site-header").is(":hidden");
    if ( closed )
       div.style.display = "block";
    else
        div.style.display = "none";
    setCookie("show", !closed, 365 );
});

});

Solution

  • You have a couple of issues here. Firstly you're defining an IIFE-like function wrapper, but you never invoke it, so your code won't run. You need to add (jQuery) to the end to pass in a reference, or use an actual document.ready event handler if that's your intention.

    Secondly, cookies only store strings, so you need to either convert the string to a boolean (which is a little bit of a minefield with JS's data typing), or alternatively you can just compare strings. Try this:

    (function($) {
      var $div = $(div);
      
      var openToggle = getCookie("show") == 'true';
      $div.toggle(openToggle);
        
      if (window.location.pathname == '/')
        $div.show();
      
      $('#Togglesite-header').click(function() {
        var closed = $("site-header").is(":hidden");
        $div.toggle(closed);
        setCookie("show", !closed, 365);
      });
    })(jQuery);

    Two further things to note. Firstly I amended this to use jQuery. If you've already loaded it, you may as well make use of its simplicity to make your code less verbose.

    Secondly, it assumes your getCookie() and setCookie() functions are working; you've not shown their implementation, but as there's lots of working examples of those I don't believe this to be your issue.