简体   繁体   中英

How to set/remove cookie with jQuery using click function

I have a button which adding/removing the extra body class on every click. I'm trying to set the proper class using jquery-cookie script. Here is my code:

$(document).ready(function() {
   var body_class = $.cookie('body_class');
   if(body_class) {
       $('body').attr('class', body_class);
   }
   else {
       $.removeCookie('body_class');
   }
   $(".contrast-btn").click(function() {
       $("body").toggleClass("extra-class");
       $.cookie('body_class', $('body').attr('class'));
   });
});

What is the problem?

When I click the button on start page, and go to the subpage the class is moving to all visited subpages - that is correct. When I click once again on button (but on subpage) the class on that subpage is removed - what is also correct. The problem is when I go to start page or other subpages (which I have visited) the extra-class is set but should be removed.

On console I have multiple cookies with different path name. Is it possible to do that after "second" click:

  1. remove the extra-class class
  2. remove all body_class cookies

Try smoething like this:

$(document).ready(function() {
   var body_class = $.cookie('body_class');
   if(body_class) {
       $('body').addClass(body_class);
   }else {
       // We already know this cookie doesn't exists at this point, so instead of trying to remove it,
       // this is where you want to SET it.
       $.cookie('body_class', "extra-class");
   }
   $(".contrast-btn").click(function() {
       $("body").toggleClass("extra-class");
       $.cookie('body_class', "extra-class");
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM