Set cookie and get cookie with JavaScript

Cover Image for Set cookie and get cookie with JavaScript
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

How to Set and Get Cookies with JavaScript

šŸŖšŸŖšŸŖ Who doesn't love cookies? And no, we're not talking about the edible kind. We're talking about cookies in the world of web development. šŸŒ

In this guide, we'll show you how to set and get cookies using JavaScript. Cookies are small pieces of data that websites store on a user's computer. They can be used to remember user preferences, track user activity, and more. šŸ–„ļø

Let's dive in and solve a common problem: setting a cookie based on a user's CSS file selection in HTML. We'll also explore how to retrieve that cookie when the user returns to the website. šŸŽØ

The Problem

Imagine you have an HTML form with a dropdown list of CSS file options. When a user selects one of the options, you want to save that choice as a cookie. The next time the user opens the HTML file, their previous CSS file selection should be applied automatically. šŸ˜Ž

The Solution

To solve this problem, we need to use JavaScript to handle the form submission and set the cookie accordingly. Here's a breakdown of the steps involved:

  1. HTML Setup: In your HTML file, set up a form element with a select element containing the CSS file options. Give the select element an id attribute so we can easily target it in JavaScript:

<form>
    Select your CSS layout:<br>
    <select id="myList">
        <option value="style-1.css">CSS1</option>
        <option value="style-2.css">CSS2</option>  
        <option value="style-3.css">CSS3</option>
        <option value="style-4.css">CSS4</option>
    </select>
</form>
  1. JavaScript Functions: Next, we'll define two JavaScript functions: cssLayout() and setCookie(). The cssLayout() function will handle the CSS file selection change event, while the setCookie() function will save the selected CSS file as a cookie:

function cssLayout() {
    document.getElementById("css").href = this.value;
}

function setCookie() {
    const selectedCss = document.getElementById("myList").value;
    const expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + 7); // Set the cookie to expire in one week
    const cookieString = `Css=${selectedCss}; expires=${expirationDate.toGMTString()}`;
    document.cookie = cookieString;
}
  1. Event Handling: We need to add an event listener to the select element in order to call the cssLayout() function whenever the CSS file selection changes. Additionally, we can add an event listener to the form element to trigger the setCookie() function when the form is submitted:

document.getElementById("myList").addEventListener("change", cssLayout);
document.querySelector("form").addEventListener("submit", setCookie);
  1. Getting the Cookie: Now that the cookie is set, we can retrieve its value using the document.cookie property. We'll define a getCookie() function to display an alert with the cookie value:

function getCookie() {
    alert(document.cookie);
}

To display the cookie value, you can call the getCookie() function at any point in your JavaScript code where you want to retrieve it.

Conclusion

With just a few lines of JavaScript, you can set and get cookies in your web application. By using cookies, you can create personalized experiences and remember user preferences. šŸŒŸ

Remember to attach the JavaScript code (event listeners and functions) to your HTML file, and you'll be all set to use cookies to save and retrieve data in your web application!

Now it's your turn! šŸš€ Try implementing cookies in your own projects and see how they can enhance the user experience. Share your experience and any questions you have in the comments below! Happy coding! šŸ˜ŠšŸ’»


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

šŸ”„ šŸ’» šŸ†’ Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! šŸš€ Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings šŸ’„āœ‚ļø Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide šŸš€ So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? šŸ¤” Well, my

Matheus Mello
Matheus Mello