How to set Cookie JavaScript | Create and get Cookie in Javascript

Last updated Mar 09, 2021


Every web developer should have to know what is cookie and how to set cookie with JavaScript. Cookie is defined as, it is a small piece of data which will be store on users computer or webserver. There are two ways to suse cookie for the web programming, one is set cookie at user browser with javascript and other is set cookie on server side.

In this post we are going to learn how to set cookie with javascript on user's browser

 

Javascript cookies are best way to store data on the web pages without using the server side scripting. We can store, read, update and delete these data from cookie.

This Javascript functionality as called client side scripting.

 

Let's get started with Cookie with Javascript

 

How to create cookie with javascript?

We have a function called document.cookie which will be used to create a cookie with javascript

 

Cookie properties

The following are the properties which helps to create a cookie with a specific name and value using JavaScript.

  • name– The name of the cookie.
  • expires– The cookie expiry time in days

 

document.cookie = "name=RRtutors";


 

So now we created a cookie with Name "RRTutors"

How much time will this cookie will be available on the user's browser, will it clear on closing the browser?

Yes, by default every cookie with destory on closing the browser, so how will to maintain cookie for a period of time

To maintain a cookie for a period of time we need to set an expiery date for each cookie

document.cookie = "name=RRtutors; expires=Wed, 10 March 2021 12:00:00 UTC";

 

Now we have done to set cookie, how to fetch the stored cookie,

 

How to Read Cookie with javascript?

To read cookie we will use document.cookie property

var mycookie= document.cookie;

 

How to Update cookie?

Update the cookie is similar to add cookie, we just need to change the data which we want to update on it.

document.cookie = "name=RRtutors; expires=Wed, 10 March 2021 12:00:00 UTC";

 

How to delete cookie in javaScript?

To delete cookie we need to pass empty values for the name of the cookie and if we added any expiery date,  just pass past date value

document.cookie = "name=; expires=Thu, 01 March 2021 00:00:00 UTC;";

 

 

Sample Example code

<!DOCTYPE html>
<html>
<head>

    <script>
function setCookie(cookie_name,value,days_to_expire) {
   var d = new Date();
   d.setTime(d.getTime() + (days_to_expire*24*60*60*1000));
   var expires = "expires=" + d.toGMTString();
   document.cookie = cookie_name + "=" + value + ";" + expires + ";path=/";
}

function getCookie(cookie_name) {
   var cname = cookie_name + "=";
   var decodedCookie = decodeURIComponent(document.cookie);
   var ca = decodedCookie.split(';');
   for(var i = 0; i < ca.length; i++){
      var c = ca[i];
      while(c.charAt(0) == ' '){
         c = c.substring(1);
      }
      if(c.indexOf(cname) == 0){
         return c.substring(cname.length, c.length);
      }
   }
   return "";
}

function deleteCookie(cookie_name) {
   var d = new Date();
   d.setTime(d.getTime() - (60*60*1000));
   var expires = "expires=" + d.toGMTString();
   document.cookie = cookie_name + "=;" + expires + ";path=/";
}

function checkCookie() {
   var user = getCookie("username");
   if(user != ""){
     alert("Welcome again " + user);
   }else{
      user = prompt("Enter your name:","");
      if (user != "" && user != null) {
        setCookie("username", user, 1);
      }
      
   }
    document.getElementById('cookieName').innerHTML = user;
    
    if(user == ""){
        var elem = document.getElementById("cookiedel");
        elem.style.display = 'none';
    }
}

function deleteCookieVal(){
    deleteCookie("username");
    location.reload();
}
</script>
</head>

<body onload="checkCookie()" style="text-align: center;">


<div class="demo-title"><h4> Store Data in Cookies with JavaScript</h4></div>
<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div class="">
                <h4 style="color: #ff9800;font-size: 20px;">Enter cookie name on dialog and refresh the page.</h4>
                <p><b>Cookie Name:</b> <span id="cookieName"></span></p>
                <button onclick="deleteCookieVal();" id="cookiedel" style="color: #FFF;
    background: #ff5722;
    padding: 10px;">DELETE COOKIE</button>
            </div>
        </div>
    </div>
</div>

</body>
</html>


      Set Cookie Javascript

 

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

253 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions