How to set Cookie using JavaScript

Objective: To learn about how to create and read the cookie using JavaScript.

Cookie is small piece of data which is saved on user device by website. It is helpful in storing any data to identify the user or to track the user. When user again visits the website, stored data can be read easily.

By the function createCookie(), you can easily create the cookie by passing the name, value (data which you want to store) and expiry date.

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 = '';
}
//setting cookie
document.cookie = name + '=' + value + expires + '; path=/';
}

You can easily read the cookie using the below function by providing cookie name.

function readCookie(name) {
var nameEQ = name + '=';
//reading the cookie
var ca = document.cookie.split(';');
//processing to get the content
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) == 0) {
//returning actual content
return c.substring(nameEQ.length, c.length);
}
}
return null;
}

Example: Example to store the user name in the cookie.

if (cookies == 'yes') {
jQuery('document').ready(function () {
//reding cookie
var cook = readCookie('YourWebsite');
if (cook != 'true') {
//calling to create the cookie if not found
createCookie('YourWebsite', 'user_name=akash', 30);
}
});
}

You can see the stored cookie in the console of the browser:

How to set Cookie using JavaScript

Dependency: You will need to include the jquery min js file to run the example. For this, you can use below line of code.

Related Blogs: Copy to clipboard in JavaScript

Akash Roshan

Akash is a PHP developer and wants to share his knowledge through Blogs. He is currently growing in the IT industry while fulfilling his own goals.

Leave a Reply

Your email address will not be published. Required fields are marked *