Essential Cookies JS Example Code Snippets

Cookies in JavaScript are essential for creating dynamic and interactive web applications. They allow data to be stored on the client side, enabling features like user preferences, authentication, and session management. Let's explore an example of using cookies in JavaScript.

a poster showing the different types of cookies and what they are labeled in each cookie
a poster showing the different types of cookies and what they are labeled in each cookie

First, let's understand how to set, get, and delete cookies using JavaScript.

different types of cookies are shown in this diagram, with the names and description below
different types of cookies are shown in this diagram, with the names and description below

Setting, Getting, and Deleting Cookies

To work with cookies, we'll use functions that follow these conventions:

the 8 cookies recipe is shown with instructions for how to make it and what to use them
the 8 cookies recipe is shown with instructions for how to make it and what to use them
  1. Setting a cookie: Set the cookie name, value, and options (expiration time, path, etc.).
  2. Getting a cookie: Retrieve the value of a specific cookie by its name.
  3. Deleting a cookie: Remove a cookie by setting its expiration date to a past date.

Setting a Cookie

the ultimate cookie recipe for 6 delicious homemade cookies
the ultimate cookie recipe for 6 delicious homemade cookies

Here's a function to set a cookie with an optional expiration time:

function setCookie(key, value, days) {
  const date = new Date();
  date.setTime(date.getTime() + (days*24*60*60*1000));
  let expires = "expires="+ date.toUTCString();
  document.cookie = key + "=" + (value || "")  + ";" + expires + ";path=/";
}

To set a cookie named "username" with a value of "John Doe" and an expiration time of 1 day:

setCookie('username', 'John Doe', 1);

Cookie Design Flavor Ideas | Baking
Cookie Design Flavor Ideas | Baking

Getting a Cookie

To retrieve the value of a cookie by its name:

function getCookie(key) {
  let name = key + "=";
  let decode = decodeURIComponent(document.cookie);
  let ca = decode.split(';');
  for(let i = 0; i 

To get the value of the "username" cookie:

a poster showing different types of cookies
a poster showing different types of cookies

getCookie('username');

Deleting a Cookie

an image of cookies with different toppings on them and the names in each one
an image of cookies with different toppings on them and the names in each one
an info sheet with different types of cookies and other desserts on the top one
an info sheet with different types of cookies and other desserts on the top one
the nine types of cookies are shown in this graphic above it is an image of different kinds
the nine types of cookies are shown in this graphic above it is an image of different kinds
inst: aidan_cookies 🩵
inst: aidan_cookies 🩵
Cookie Recipes – 6 Easy Homemade Cookies That Are Soft, Chewy & Bakery Style
Cookie Recipes – 6 Easy Homemade Cookies That Are Soft, Chewy & Bakery Style
an assortment of cookies with different flavors and toppings
an assortment of cookies with different flavors and toppings
an image of different types of cookies
an image of different types of cookies
Healthy Cookies
Healthy Cookies
the ultimate cookie recipe is shown in this poster
the ultimate cookie recipe is shown in this poster
an advertisement for cookies and ice creams with the words pick your base on it
an advertisement for cookies and ice creams with the words pick your base on it
six types of cookies arranged on top of a white piece of paper with the words, 6 types of cookies
six types of cookies arranged on top of a white piece of paper with the words, 6 types of cookies
a poster with cookies for guilt - free cravings and high protein cookies
a poster with cookies for guilt - free cravings and high protein cookies
COOKIES
COOKIES
a box filled with lots of different types of cookies on top of eachother
a box filled with lots of different types of cookies on top of eachother
an image of cookies with different flavors
an image of cookies with different flavors
Cookie Cravings Club
Cookie Cravings Club
chocolate chip cookies are arranged on a baking sheet and labeled with the names of each cookie
chocolate chip cookies are arranged on a baking sheet and labeled with the names of each cookie
the 9 types of cookies you can eat
the 9 types of cookies you can eat
😋
😋
a white board with different types of cookies on it
a white board with different types of cookies on it

To remove a cookie, set its expiration date to the past:

function deleteCookie(key) {
  document.cookie = key + '=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';
}

To delete the "username" cookie:

deleteCookie('username');

Cookies in Practice: Remembering User Preferences

Cookies can store user preferences, like dark mode or theme choices. Let's create an example of changing the website's theme based on user preference stored in a cookie.

Changing the Theme

First, we'll create an element with an ID "theme-toggle" in our HTML:

<button id="theme-toggle">Toggle Dark Mode</button>

Now, we'll write JavaScript to toggle the theme and set/get the user's preference:

Javascript

let themeToggle = document.getElementById('theme-toggle');
let body = document.body;
let themeCookie = "theme";

function toggleTheme() {
  if (getCookie(themeCookie) === 'dark') {
    setCookie(themeCookie, 'light', 30);
    body.classList.remove('dark-mode');
  } else {
    setCookie(themeCookie, 'dark', 30);
    body.classList.add('dark-mode');
  }
}

themeToggle.addEventListener('click', toggleTheme);
if (getCookie(themeCookie) === 'dark') {
  body.classList.add('dark-mode');
}

This code sets up an event listener for the "theme-toggle" button that switches the theme and sets/updates the cookie. The initial page load checks the cookie and applies the user's preferred theme.

Cookies are an essential part of building interactive and personalized web experiences. They enable features like user preferences, authentication, and session management across different requests. In this example, we've demonstrated how to set, get, and delete cookies, and also how to use cookies to store and retrieve user preferences. By leveraging cookies, we can create more engaging and intuitive web applications.

Related Articles

W3schools Js Variables W3schools Js String W3schools Javascript Yield W3schools Js Foreach W3schools Js Tester Html Js Innerhtml Https Www W3schools Com Js Js_if_else Asp W3schools Js Button W3schools React Js Interview Questions W3schools React Js Hooks