How to make JavaScript cookie
Learn how to create a JavaScript cookie with an example: store, access, and delete.
Making JavaScript Cookie
Cookies are small pieces of data that websites store in the browser and use to remember user preferences. They are used in many websites and web applications to save user information and to track user data. JavaScript can be used to set, retrieve, and delete cookies.
To create a cookie using JavaScript, you need to use the document.cookie
property. This property allows you to set, retrieve, and delete cookies. To create a cookie, you need to specify a name, a value, and an expiration date.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2020 12:00:00 UTC; path=/";
The example above creates a cookie named “username” with the value “John Doe”. The cookie will expire on December 18th, 2020. The path is set to the root of the site, which means the cookie will be available on all pages of the site.
You can also retrieve the value of a cookie using JavaScript. To do this, you need to use the document.cookie
property. This property returns a string containing all the cookies for the current page. You can then use the split()
method to split the string and retrieve the value of the cookie.
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
var username = getCookie('username');
The example above uses a function to retrieve the value of a cookie. The function takes the name of the cookie as an argument and returns the value of the cookie. This is a useful way to retrieve a cookie value without having to parse the entire cookie string.
Finally, you can delete a cookie using JavaScript. To delete a cookie, you need to set the expires
property to a date in the past. This will cause the browser to delete the cookie.
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
The example above sets the expires
property to a date in the past, which will cause the browser to delete the cookie. This is a simple way to delete a cookie using JavaScript.
In this tutorial, we've seen how to use JavaScript to set, retrieve, and delete cookies. Cookies are a useful way to store user information and track user data, and JavaScript makes it easy to work with cookies.