Search code examples
jquerycookiesreload

Set cookie in a funtion, then check on page reload and do something


I would like to set a value for a cookie at the end of a function and on page reload, check for the existence of that code. Something like:

function onObjectDrag() {
// save code
$.cookie("saved", 1);
location.reload();
}

Then when the page is refreshed, check if that cookie exists and if so, do something then delete the cookie. If not, don't do anything.


Solution

  • Do not call onObjectDrag() without any condition or after you set the cookie to zero or else you will end up with a recursion.

    function onObjectDrag() {
        setCookie('saved', 1, 100);
        location.reload();
    }
    
    $( document ).ready(function() {
        var x = getCookie('saved');
        if (x == 1) {
            //do something
            setCookie('saved', 0, 100);
        }
    });
    
    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
        }
        return "";
    }
    
    function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }