0

I am trying to use JavaScript to create and delete cookies. The way I have it setup is that when the user clicks on the accept button I create a cookie. If they click on the decline button I remove it.

However I find each time I try to remove the cookie it still remains. Would anyone be able to advise on what I am doing wrong?

CREATE COOKIE:

//Create Cookie
function createCookie(name, value, expires, path, domain) {
  var cookie = name + "=" + escape(value) + ";";
  if (expires) {
    // If it's a date
    if(expires instanceof Date) {
      // If it isn't a valid date
      if (isNaN(expires.getTime()))
       expires = new Date();
    }
    else
      expires = new Date(new Date().getTime() + parseInt(expires) * 1000 * 60 * 60 * 24);

    cookie += "expires=" + expires.toGMTString() + ";";
  }

  if (path)
    cookie += "path=" + path + ";";
  if (domain)
    cookie += "domain=" + domain + ";";
  document.cookie = cookie;
}

//Delete Cookie
function deleteCookie(name, path, domain) {
    console.log('deleting ' + name + ' cookie...');
    createCookie(name, "", -1, path, domain);
}

//Accept Button Click - CREATE COOKIE
$('#accept').click(function(e){
    e.preventDefault();
    console.log("You've accept our cookie policy!")
    createCookie("MyCookie", "Yummy", 2, "/", ".xyz.com");
});

//Decline Button Click - DELETE COOKIE
$('#decline').click(function(e){
    e.preventDefault();
    console.log("You've declined our cookie policy!");
    deleteCookie("myCookie", "/", ".xyz.com");
});
Script47
  • 14,230
  • 4
  • 45
  • 66
Javacadabra
  • 5,578
  • 15
  • 84
  • 152
  • 2
    Possible duplicate of [Delete cookie by name?](https://stackoverflow.com/questions/10593013/delete-cookie-by-name) – Kaddath Aug 24 '17 at 10:32
  • 1
    @GolezTrol not with empty value but with an expired or previous time instance – Sagar V Aug 24 '17 at 10:32

1 Answers1

0

In order to delete a cookie set, the expires date to something in the past.

Your code is right, just pass any passed date in expires value.

Harsh Patel
  • 6,334
  • 10
  • 40
  • 73