1

I have a button that can be toggled on and off by adding and removing classes, when clicked to off, I need it to stay in that state and vice versa, the cookie I assigned to the 'off' state works but when I want to toggle it back to on I can't remove the cookie.

$(document).ready(function () { $(".button2").click(function () { if($(".toggle2").hasClass("toggleOn")) { $(".toggle2").removeClass("toggleOn"); $(".toggle2").addClass("toggleOff"); $.cookie('setting1', 'off', { expires: 1, path: '/', domain: '#' }); } else { $(".toggle2").removeClass("toggleOff"); $(".toggle2").addClass("toggleOn"); $.cookie('setting1', null, { expires: 1, path: '/', domain: '#' }); } }); }); $(function() { if($.cookie('setting1') == null) { } else { $(".toggle2").removeClass("toggleOn"); $(".toggle2").addClass("toggleOff"); $(".buttonON2").removeClass("buttOnAnimate"); $(".buttonON2").addClass("buttOnAnimateRemove"); $(".buttonOFF2").removeClass("buttOffAnimateremove"); $(".buttonOFF2").addClass("buttOffAnimateADD"); }; }); 

I'm fairly new to the concept of cookies, I read up that assigning null to the value would follow the if statement of the cookies which is nothing thereby ignoring the else statement. Any suggestions would be appreciated.

3
  • If your goal is to remove the cookie you can use $.removeCookie("cookie_name"); Commented Oct 4, 2016 at 9:30
  • use localStorage for new HTML5 supported browsers. Ex.stackoverflow.com/a/39832070/6608101 Commented Oct 4, 2016 at 9:30
  • @Franco Yes, I do. Commented Oct 4, 2016 at 9:33

1 Answer 1

1

Use removeCookie to remove a cookie

$.removeCookie('setting1'); 

for newer version of jquery.cookie use

Cookies.remove('setting1'); 
Sign up to request clarification or add additional context in comments.

1 Comment

For some reason this didn't work, I don't know If I've got an outdated jquery.cookie.js file. I did find an alternative - $.cookie('setting1', '', { expires: -1, path: '#' }); - Not sure if It's recommended though

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.