IT & Programming

Creating cookie with Javascript

As compared to PHP, it is a but complex to create a cookie with JavaScript. Below is custom made JavaScript cookie creation function that can create a cookie easily. All you have to do is to pass 3 parameters. name of the cookie, value of the cookie and expiration value in days.

Function

function createCookie(name, value, days) {
 
   if (days) {
 
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();

    } else

        var expires = "";

    document.cookie = name + "=" + value + expires + "; path=/";
}

Calling The Function

createCookie('country', 'Belgium', 7);

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *