0

I want to delete browser cookie when a button clicked. I have checked my code and found that onclick event working and execute the deleteCookie function but cookie not deleted.

Below is my code:

$(".close-conversation").on("click", function (e) {
      e.preventDefault();
      console.log('button clicked'); 
      deleteCookie('instanceId');
      deleteCookie('chatWindow');
      deleteCookie('userdataLoaded');
 });


//deleteCookie function

function deleteCookie(cname) {
   document.cookie = cname + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
   console.log('cookie deleted')
 }

please help me to find the mistake. Thanks in advance.

ARi
  • 78
  • 14
  • 1
    Did you try setting the path too ? `document.cookie = cname + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";` – Zenoo Aug 03 '17 at 07:49
  • Your code is working perfectly, check the fiddle https://jsfiddle.net/ku3zgLqe/ – Shiladitya Aug 03 '17 at 08:00
  • Possible duplicate of [Delete cookie by name?](https://stackoverflow.com/questions/10593013/delete-cookie-by-name) – Hassan Imam Aug 03 '17 at 08:02

1 Answers1

0

You have hard coded expires value, set it to current time to delete cookie at the moment.

function deleteCookie(cname) {
    var d = new Date();
    d.setTime(d.getTime());
    var expires = "expires="+d.toUTCString(); 
    document.cookie = cname + '=;'+ expires;
    console.log('cookie deleted')
}
Selvakumar
  • 527
  • 2
  • 13