Cookies are small text files stored on a user’s device by their web browser. They allow websites to store information about a user’s interactions with the site, such as preferences or login details. In this tutorial, we will explore how to work with cookies in JavaScript.
Setting Cookies
To set a cookie in JavaScript, you can use the document.cookie
property. This property allows you to read and write cookies for the current document. Here is an example of how to set a cookie:
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
This function takes three arguments: name
, value
, and days
. The name
argument is the name of the cookie, the value
argument is the value of the cookie, and the days
argument is the number of days until the cookie expires.
Getting Cookies
To get a cookie in JavaScript, you can use the document.cookie
property again. However, this time you need to parse the cookie string to extract the value of the cookie you are interested in. Here is an example of how to get a cookie:
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
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) return c.substring(nameEQ.length,c.length);
}
return null;
}
This function takes one argument: name
. The function splits the cookie string into an array of individual cookies and then loops through the array to find the cookie with the specified name.
Removing Cookies
To remove a cookie in JavaScript, you can set the expiration date of the cookie to a date in the past. Here is an example of how to remove a cookie:
function eraseCookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
This function takes one argument: name
. The function sets the expiration date of the cookie to January 1, 1970, which is in the past.
Using Cookies with Forms
Cookies can be used with forms to store user preferences or other information. For example, you could use a cookie to store the selected value of a dropdown list:
function cssSelected() {
var cssSelected = document.getElementById("myList").value;
setCookie("selectedCSS", cssSelected, 7);
}
document.addEventListener("DOMContentLoaded", function() {
var selectedCSS = getCookie("selectedCSS");
if (selectedCSS) {
document.getElementById("myList").value = selectedCSS;
}
});
This code sets a cookie called "selectedCSS" when the user selects an option from the dropdown list. When the page loads, it checks for the existence of the cookie and sets the selected value of the dropdown list to the value stored in the cookie.
Best Practices
Here are some best practices to keep in mind when working with cookies:
- Use the
path
attribute to specify the path of the cookie. This can help prevent cookies from being accessed by other parts of your website. - Use the
domain
attribute to specify the domain of the cookie. This can help prevent cookies from being accessed by other websites. - Use the
secure
attribute to specify that the cookie should only be transmitted over a secure connection (HTTPS). - Be mindful of the size limit of cookies. Most browsers have a limit of 4KB per cookie.
- Be aware of the privacy implications of using cookies. Make sure to inform your users about the use of cookies and provide them with options to opt out.
Conclusion
Cookies are a powerful tool for storing information on the client-side. By following best practices and using the document.cookie
property, you can create robust and secure cookie-based solutions for your website.