Preserve toggled states on page load/refresh with jQuery Cookies

136 Views Asked by At



I am trying to implement accessibility features on a site I'm working on. I have three toggle buttons (font size, highlighted links and color invert) and I want to preserve the toggled states on page load/refresh using jQuery Cookies. I've read other threads on the subject but I'm just too inexperienced to get my specific scenario to work.

$(document).ready(function(){
    $("button.type-size").click(function(){
        $("body").toggleClass("accessibility-font");
        $("button.type-size").toggleClass("on");
    });
    $("button.links").click(function(){
        $("a").toggleClass("accessibility");
        $("button.links").toggleClass("on");
    });    
    $("button.contrast").click(function(){
        $("body, img, .site-branding, .accessibility-bar, .no-invert, a, button").toggleClass("invert");
        $("button.contrast").toggleClass("on");
    });
});


Thanks in advance!

1

There are 1 best solutions below

0
Fadermoll On

Found a solution. This is how I check if a button is pressed or not.

$(document).ready(function(){
  var sel = $.cookie("accessibility"); // get the cookie
   console.log("from cookie:"+sel,sel!=true);
  sel = sel=="true";
   $("body, a").toggleClass("accessibility",sel); // initial
   console.log("after test:"+sel,$("body, a").hasClass("accessibility"));

 $("button.links").on("click",function() {
    $("body, a").toggleClass("accessibility");
    var $this = $(this);
    sel = !sel;  
    $.cookie("accessibility", sel,{ expires: 1, path: '/' });
 });
});