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.
Step 1: To set the cookie on user device
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=/'; }
Step2: To read the cookie
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:
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