In the bustling city of Codeville, the Grand Council of Developers sought to enhance their web applications by learning about JavaScript cookies. Cookies are small pieces of data stored on the user’s computer that help remember information between sessions. Join us as we explore the basics of cookies, how to create, read, and delete them using JavaScript.
Mayor Binary began the lesson. “Cookies are small text files that websites store on a user’s browser to remember information across different sessions. They are used for various purposes, such as tracking user activity, storing preferences, and managing login sessions.”
Types of Cookies
The council learned how to create cookies using JavaScript. Cookies are created by setting the document.cookie property.
Basic Cookie Creation
javascript
Copy code
// Create a cookie
document.cookie = “username=Alice”;
Cookie with Expiration Date
You can set an expiration date for a cookie using the expires attribute.
javascript
Copy code
// Create a cookie that expires in 7 days
let date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days in milliseconds
let expires = “expires=” + date.toUTCString();
document.cookie = “username=Alice; ” + expires;
Cookie with Path
You can set a path for a cookie using the path attribute, which specifies the URL path that must exist for the cookie to be sent.
javascript
Copy code
// Create a cookie with a path
document.cookie = “username=Alice; path=/”;
Mayor Binary explained how to read cookies. The document.cookie property returns all cookies in a single string, and the council learned how to parse this string to extract individual cookies.
javascript
Copy code
// Function to get the value of a specific cookie
function getCookie(name) {
let cookieArr = document.cookie.split(“;”);
for (let i = 0; i < cookieArr.length; i++) {
let cookiePair = cookieArr[i].split(“=”);
// Remove whitespace at the beginning of the cookie name and compare it to the given string
if (name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
// Return null if not found
return null;
}
// Example usage
let username = getCookie(“username”);
if (username) {
console.log(“Username: ” + username);
} else {
console.log(“Username cookie not found”);
}
The council learned how to delete cookies by setting the expires attribute to a past date.
javascript
Copy code
// Function to delete a cookie
function deleteCookie(name) {
document.cookie = name + “=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;”;
}
// Example usage
deleteCookie(“username”);
The council decided to create a practical example by storing and retrieving user preferences using cookies.
HTML
html
Copy code
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Cookie Example</title>
</head>
<body>
<h1>Welcome to Codeville</h1>
<label for=”theme”>Choose a theme:</label>
<select id=”theme” onchange=”setTheme(this.value)”>
<option value=”light”>Light</option>
<option value=”dark”>Dark</option>
</select>
<script src=”script.js”></script>
</body>
</html>
JavaScript
javascript
Copy code
// Function to set a cookie
function setCookie(name, value, days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
let expires = “expires=” + date.toUTCString();
document.cookie = name + “=” + value + “; ” + expires + “; path=/”;
}
// Function to get a cookie
function getCookie(name) {
let cookieArr = document.cookie.split(“;”);
for (let i = 0; i < cookieArr.length; i++) {
let cookiePair = cookieArr[i].split(“=”);
if (name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}
// Function to delete a cookie
function deleteCookie(name) {
document.cookie = name + “=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;”;
}
// Function to set the theme
function setTheme(theme) {
setCookie(“theme”, theme, 7); // Store the theme in a cookie for 7 days
document.body.className = theme;
}
// Function to load the theme from the cookie
function loadTheme() {
let theme = getCookie(“theme”);
if (theme) {
document.getElementById(“theme”).value = theme;
document.body.className = theme;
}
}
// Load the theme when the page loads
window.onload = loadTheme;
By mastering JavaScript cookies, the Grand Council of Developers in Codeville learned how to store and manage user data efficiently. Cookies are essential for enhancing user experience by remembering preferences, managing sessions, and tracking user activity. Feel free to experiment with the provided examples and expand upon them to suit different scenarios. If you have any questions or need further assistance, I’m here to help. Happy coding!