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.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252

1 Answers1

1

Use removeCookie to remove a cookie

$.removeCookie('setting1');

for newer version of jquery.cookie use

Cookies.remove('setting1');
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
  • 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 – jay stephens Oct 04 '16 at 09:49