0

My script sets a cookie named stop_mobi with JavaScript. I am then trying to delete the cookie when a user clicks a link with an onclick event however when I test this the cookie is not deleted. Any pointers to where I am going wrong would be greatly appreciated. Thanks.

<script type="text/javascript">
    // set stop_mobi cookie for test purposes


    function setCookie(cookieName, cookieValue, nDays) {
        var today = new Date();
        var expire = new Date();
        if (nDays == null || nDays == 0) nDays = 1;
        expire.setTime(today.getTime() + 3600000 * 24 * nDays);
        document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
    }
    setCookie("stop_mobi", "yes", "5");

    function deleteCookie(name) {
        document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        alert('Cookie deleted');
    }
</script>

<a href="" onclick="deleteCookie('stop_mobi');">Delete cookie</a>
David G
  • 94,763
  • 41
  • 167
  • 253
Ben Paton
  • 1,432
  • 9
  • 35
  • 59
  • 1
    possible duplicate of [javascript - delete cookie](http://stackoverflow.com/questions/2144386/javascript-delete-cookie) – Basic Dec 06 '12 at 20:26
  • when you call the deleteCookie function, does the alert execute? – Jonah Katz Dec 06 '12 at 20:29
  • Seems to work here: http://jsfiddle.net/SLaZj/ – Chase Dec 06 '12 at 20:32
  • Yes the alert does execute when deleteCookie is called. It does seem to work on the jsfiddle example. I wonder why it doesn't work on my server... maybe the page is reloading and the cookie is being set again after I ok the alert? – Ben Paton Dec 06 '12 at 20:38
  • 1
    I suspect it's a problem with mis-matching the domain name the cookie is being set for and cleared for... Did you see the linked duplicate which addresses that issue? – Basic Dec 06 '12 at 21:06

0 Answers0