JavaScript cookies are data files that contain the information provided by users. These files are stored on users' computers. This tutorial explains how cookies are created and used to enhance websites.
You will learn how to write them in JavaScript from scratch, going through all of the necessary parameters. This tutorial also covers the ways to modify, update, and delete cookies. Furthermore, you will learn to make JavaScript set cookie.
Contents
JavaScript Cookies: Main Tips
- When a user logs off of a website, the server forgets everything about the user. In order for it to remember user's information, cookies are used.
- Cookies are small data files that are stored on your computer.
- They are meant to store user information for a web page to use.
A Basic Example
What are cookies? It is data stored on the computer in name-value pairs.
See the example below. You can see exactly such pair that is used to contain the username a visitor of a webpage has entered when logging in:
username=jogger66
Working with Cookies
Creating
In JavaScript, the document.cookie
property might be used to create, delete and read cookies.
The example below displays the first step we need to take - creating a cookie:
document.cookie = "name=jogger66";
By default, cookies are instantly deleted once you close the browser. However, a defined expiry date can be added to the cookies too:
document.cookie = "name=jogger66; expires=Fri, 11 Dec 2019 14:00:00 UTC";
The path
parameter specifies the path to which the cookie belongs. By default, the path is the current page:
document.cookie = "name=jogger66; expires=Fri, 11 Dec 2019 14:00:00 UTC; path=/";
Reading
The example provided below shows how to read cookies in JavaScript:
var xyz = document.cookie;
Note: the method will return all the cookies in one string list (cookieOne=valueOne; cookieTwo=valueTwo...)
Changing
The process of changing cookies in JavaScript is the same as creating them. The old cookie's value is deleted by overwriting it:
document.cookie = "name=newJogger; expires=Thu, 22 Dec 2022 22:00:00 UTC; path=/";
Deleting
To delete a cookie, set its expiry date to a date in the past. As it has already passed, the system understand the cookie as no longer valid:
document.cookie = "name=newJogger; expires=Thu, 22 Dec 2022 22:00:00 UTC; path=/";
Note: it is always better to define the path when deleting a cookie to make sure you are removing the right one. Some browsers may not even allow deletion if the path is not set.
Setting
Now that you know what cookies are, the following paragraphs will explain how to set, get, and check user's cookies. This first example shows how JavaScript set cookie method works.
The function creates a cookie by adding together the cookie name (cookName
), the cookie value (cookValue
), and the expires
string (expiry):
function setCookie(cookName, cookValue, expiry) {
var dt = new Date();
dt.setTime(dt.getTime() + (expiry*24*60*60*1000));
var expires = "expires="+ dt.toUTCString();
document.cookie = cookName + "=" + cookValue + ";" + expiry + ";path=/";
}
Getting
Then, we create a function that returns the value of a specified cookie. It takes the cookie name as a parameter (cookName
), splits each element of the document.cookie
into an array (cookArray
), then loops through all the elements and reads each value.
If a cookie is found c.indexOf(name) == 0
, its value is returned, if not -- ""
is returned:
function getCookie(cookName) {
var cname = cookName + "=";
var deCookie = decodeURIComponent(document.cookie);
var cookArray = decodedCookie.split(';');
for(var i = 0; i < cookArray.length; i++) {
var c = cookArray[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(cname) == 0) {
return c.substring(cname.length, c.length);
}
}
return "";
}
Checking
The last thing we will do is check the cookie.
If a function finds an existing cookie, it will display a greeting. If not, it will ask a user to enter his name. Then, it will save the new information and set a cookie:
function checkCookie() {
var firstname = getCookie("firstname");
if (firstname != "") {
alert("Welcome again " + firstname);
} else {
firstname = prompt("Enter name:", "");
if (firstname != "" && firstname != null) {
setCookie("firstname", firstname, 365);
}
}
}
A Finished Cookie
We went through all the steps of handling a JavaScript cookie step by step. Did you get it all? Fantastic!
Now, let's see all the parts described above joined and displayed together. The result is a working cookie, ready to be used on a website:
function setCookie(cookName, cookValue, expiry) {
var dt = new Date();
dt.setTime(dt.getTime() + (expiry*24*60*60*1000));
var expires = "expires="+ dt.toUTCString();
document.cookie = cookName + "=" + cookValue + ";" + expiry + ";path=/";
}
function getCookie(cookName) {
var cname = cookName + "=";
var deCookie = decodeURIComponent(document.cookie);
var cookArray = decodedCookie.split(';');
for(var i = 0; i < cookArray.length; i++) {
var c = cookArray;
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(cname) == 0) {
return c.substring(cname.length, c.length);
}
}
return "";
}
function getCookie(cookName) {
var cname = cookName + "=";
var deCookie = decodeURIComponent(document.cookie);
var cookArray = decodedCookie.split(';');
for(var i = 0; i < cookArray.length; i++) {
var c = cookArray;
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(cname) == 0) {
return c.substring(cname.length, c.length);
}
}
return "";
}
}
JavaScript Cookies: Summary
- You can use cookies to store user information.
- You can use cookies for various purposes, such as greeting a user.
- Cookies can have an expiration date, be reset and changed anytime.