Guide to Create, Get, Delete & Display Cookies - Javascript
close
Guide to Create, Get, Delete & Display Cookies - Javascript

Guide to Create, Get, Delete & Display Cookies - Javascript

Guide to Create, Get, Delete & Display Cookies - Javascript

If you want to store user data then cookies are the best option to do that specially when you are not having any hosting like if you are blogger user then it's the best choice to use cookies to store users information without buying hosting and today in this article I am going to tell you and explain you how you can create, get, delete and display cookies.

Yes we will cover up all the things listed above and will create separate functions for all of them and make them work.

It is not too much difficult to make and read cookies I will provide you the functions with source code you will see that this is not too much difficult if you are a web designer or developer.

First of all we will see how we can create cookies this is a simple function that can help you to create cookies by providing specified values when running this function for example if you want to run this function you have to provide cookie name, cookie value, and the expiration date of cookie you don't have to provide the exact date you can simply provide the number of days.

Set Cookie Javascript Function:

/**
 * Set a cookie
 * @param {String} cname, cookie name
 * @param {String} cvalue, cookie value
 * @param {Int} exdays, number of days before the cookie expires 
 */
function setCookie(cname,cvalue,exdays) {
    var d = new Date(); //Create an date object
    d.setTime(d.getTime() + (exdays*1000*60*60*24)); //Set the time to exdays from the current date in milliseconds. 1000 milliseonds = 1 second
    var expires = "expires=" + d.toGMTString() + ";path=/"; //Compose the expirartion date
    window.document.cookie = cname+"="+cvalue+"; "+expires;//Set the cookie with value and the expiration date
}

In the above function I have explained if you run this function this function will create a cookie if you want to run this function you have to give values of three variable that are defined in the function you can see the demo of this cookies the running this function in your localhost server.

To Run This Function use Following code:

setCookie(cname,cvalue,exdays);

Here cname will be the name of cookie
cvalue will be the cookie value
exdays will be the number of days after which this cookie will be expired.

Get Cookie Javascript function:

Now after we have created or set a cookie now it's time to get or retrieve that cookie now here we will create another function with the name getCookie and in that function we will have to provide the cookie name which you want to get or retrieve from the cookie list.

/**
 * Get a cookie
 * @param {String} cname, cookie name
 * @return {String} String, cookie value 
 */
function getCookie(cname) {
    var name = cname + "="; //Create the cookie name variable with cookie name concatenate with = sign
    var cArr = window.document.cookie.split(';'); //Create cookie array by split the cookie by ';'
     
    //Loop through the cookies and return the cooki value if it find the cookie name
    for(var i=0; i<cArr.length; i++) {
        var c = cArr[i].trim();
        //If the name is the cookie string at position 0, we found the cookie and return the cookie value
        if (c.indexOf(name) == 0) 
            return c.substring(name.length, c.length);
    }
     
    //If we get to this point, that means the cookie wasn't find in the look, we return an empty string.
    return "";
}

To Run this function Use The Following Code:

getCookie(cname)
Make sure to replace cname with the name of cookie which you want to get.

Delete Cookie Javascript Function:

Now we will create another function which will help us to delete a cookie by providing a cookie name and you have to specify the cookie name while running this function.

/**
 * Delete a cookie
 * @param {String} cname, cookie name
 */
function deleteCookie(cname) {
    var d = new Date(); //Create an date object
    d.setTime(d.getTime() - (1000*60*60*24)); //Set the time to the past. 1000 milliseonds = 1 second
    var expires = "expires=" + d.toGMTString(); //Compose the expirartion date
    window.document.cookie = cname+"="+"; "+expires;//Set the cookie with name and the expiration date
 
}

To Run this Function Use Following Code:

deleteCookie(cname)
While running this function you should replace cname with the name of cookie which you want to delete.

Display All Cookies Javascript Function:

These three functions which are listed above are very much useful and important now if you want to display all of the cookies which you have created you can use the function provided below.

/**
 * Display all the cookies
 */
function disPlayAllCookies()
{
    var cookieDiv = window.document.getElementById('cookies');//Get the cookies div element
    var cArr = window.document.cookie.split(';'); //Create cookie array by split the cookie by ';'
     
    //Loop through all the cookies and display them with cookie name = cookie value
    for(var i=0; i<cArr.length; i++)
    {
        var pElm = window.document.createElement("p");//Create a p element to hold the cookie name and cookie value
        pElm.innerHTML=cArr[i].trim();//Put the cookie name and cookie value in the p elment
        cookieDiv.appendChild(pElm);//Append the p to the cookies div element
    }
}

To Run this Function use Following Code:

<div id="cookies"></div>
<script>
disPlayAllCookies();
</script>

Above function will display all the cookie which are created in a list.

Delete All Cookies Javascript Function:

Now here is a function by which you can delete all the cookies at once without deleting one by one and this function will help you to do that easily.
function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 2020 00:00:00 GMT";
    }
}

To Run this Function use Following Code:



Conclusion:

That's it in this today's article I have explained you and provided you the JavaScript code to create, get, delete, display cookies.

I hope now your all doubts about cookies are cleared now and now you can create, get, delete and display cookies easily if you want to edit any cookie value you don't have to create a separate function for that when a new cookie is created it will be replaced with the previous one you don't have to create edit function for that.

Good Luck.

Disqus Codes

No comments

Notifications

Disqus Logo