Managing cookies using JavaScript functions

Is there a way to set a cookie based on the CSS file selected in my HTML? I have a form with a list of options, each representing a different CSS file. I want to save the selected file to a cookie that lasts for a week, so the next time the HTML file is opened, it will remember the previous selection.

Check out the JavaScript code below:

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

function setCookie(){
    var date = new Date("February 10, 2013");
    var dateString = date.toGMTString();
    var cookieString = "Css=document.getElementById("css").href" + dateString;
    document.cookie = cookieString;
}

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

Here's the HTML code snippet:

<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>

Answer №1

This code simplifies the process of setting, getting, and erasing cookies in JavaScript:

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=/";
}
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;
}
function eraseCookie(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Usage example:

setCookie('ppkcookie', 'testcookie', 7);

var x = getCookie('ppkcookie');
if (x) {
    // Do something with x
}

Source - http://www.quirksmode.org/js/cookies.html

This page was updated today, so the information provided is current.

Answer №2

Forget about w3schools, these superior references are a game-changer:

Take a look at some code snippets inspired by these references:

// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// sets the cookie cookie2 (without overwriting cookie1)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

And if that's not enough, the Mozilla reference even offers a convenient cookie library for your use.

Answer №3

For information about working with JavaScript Cookies, visit W3Schools.com. Here, you can learn how to set and retrieve cookie values using JavaScript.

The setCookie and getCookie methods outlined on the website can be used for this purpose.

Here's an example of how the code may appear:

<script>
function setCookie(cookieName, value, expirationDays) {
    var expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + expirationDays);
    var cookieValue = escape(value) + ((expirationDays == null) ? "" : "; expires=" + expirationDate.toUTCString());
    document.cookie = cookieName + "=" + cookieValue;
}

function getCookie(cookieName) {
    var i, x, y, cookiesArray = document.cookie.split(";");
    for (i = 0; i < cookiesArray.length; i++) {
        x = cookiesArray[i].substr(0, cookiesArray[i].indexOf("="));
        y = cookiesArray[i].substr(cookiesArray[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == cookieName) {
            return unescape(y);
        }
    }
}

function cssSelected() {
    var selectedCSS = $('#myList')[0].value;
    if (selectedCSS !== "select") {
        setCookie("selectedCSS", selectedCSS, 3);
    }
}

$(document).ready(function() {
    $('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
    <option value="select">--Select--</option>
    <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>

Answer №4

This question seems like it requires a broad answer that includes reusable code for handling cookies as key-value pairs.

The code snippet below, sourced from MDN, provides a reliable and UTF-safe way to interact with cookies:

var docCookies = {
  // Functions for handling cookies
};

It's worth noting that Mozilla has conducted tests to validate the functionality of this code across different scenarios.

For an alternative approach, you can also check out another snippet available here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customize Your Google Maps with Checkboxes for Style Options

Trying to make dynamic changes in the style of a Google Maps using checkboxes. Some checkboxes control colors of features, while others control visibility. Having trouble figuring out how to combine different features of styles since they are not strings ...

Consolidate radio group in Vuetify platform

I'm having trouble centering the v-radio-group. Here's my current setup: <v-container grid-list-md text-xs-center> <v-form ref="form"> <div v-if="question.question_type == 'YESNO' "> <v-radio-group ...

Effortlessly submit multiple forms at once with just a single click using the WordPress form

One issue I'm experiencing is that the forms on my site are generated using shortcodes. I have a suspicion that the buttons I created, which lead to submission form1 and then form2, may not be working properly because of this. This is the current set ...

Issues with PHP code not displaying properly in HTML email design

I am struggling to understand why some of my PHP code is not rendering correctly in an HTML email that I am working on. The following is an excerpt from the code (with most of the HTML elements removed): $messaget = " <html> <head> <title&g ...

The React.js navigation bar hamburger menu refuses to close when toggled

Currently, my team and I have developed a react.js application together. The Navbar feature is functioning correctly, except for a small issue. When the Navbar is toggled using the Hamburger menu on a smaller screen, it opens successfully, but the toggle a ...

Utilizing Smarty Template: Combining <li> elements from separate <ul> tags for a seamless display

On my Prestashop website, I have implemented the "Advanced Homepage Product List" module. I removed the category names from the titles to have my items sorted without displaying the category names. Currently, this is how it appears: https://i.stack.imgur. ...

Trouble with CSS styling arising when launching the MVC application on IIS

Currently working on a website in ASP.Net MVC 5. I am trying to test it on my local IIS (version 8), but encountering an issue where the CSS styling is not being applied. In my _layout.cshtml file, I opted for direct link tags instead of using bundles. &l ...

Having trouble with Vue.js image force download not functioning properly with anchor tags?

Currently, I am utilizing Laravel in conjunction with Vue.js. I have had the requirement to forcibly download an image on the browser, but unfortunately, it is not functioning as expected. var link = document.createElement('a'); link.href = &apo ...

Having trouble adding your own styling to bootstrap-4 using a custom CSS file?

Here is the code I used to connect my two stylesheets, with the custom css file being linked second as per what I believe is the correct way to do it. <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href=" ...

Developing a Rails application integrated with Pusher or Faye for real

I've been tasked with creating an app similar to this: I'm facing challenges in updating the bids. I am considering using technologies like Pusher or Faye ( or ) and subscribing to each event. However, I'm wondering if there is a more elega ...

Converting input dates in nest.js using TypeScript formatting

Is it possible to set a custom date format for input in nest.js API request body? For example, like this: 12.12.2022 @ApiProperty({ example: 'ADMIN', description: 'Role name', }) readonly value: string; @ApiProperty({ ...

Incorporate a background image with the JavaScript CSS property

I'm having trouble adding a background image using the Javascript CSS property in my code. When I directly add the 'url', it works fine. Could the issue be with the 'weatherImage' variable? Javascript var OpenWeatherKey = ' ...

Issues with redirection to registration page in PHP Slim framework

When I access localhost/path/home, it takes me to the homepage where I can either login or signup. Clicking on either option should redirect me to localhost/path/login or localhost/path/signup respectively for the login or signup page. However, there seem ...

The bond between Node.js and Express

I'm intrigued by the relationship between Node.js and Express. Here is my Node.js server creation code: const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('./https1/key.pem&ap ...

Morris Chart Bar Graph now comes with a sleek horizontal scroll bar feature,

I have been using morris bar charts without any issues until I decided to test it with a large dataset. Now, my graph is displaying like this: Bar Graph After searching various platforms for a solution, it seems that Morris chart does not support scrollin ...

What is the purpose of adding "/dist" to the library import statement?

Currently, I am in the process of developing a react component library using vite as my primary build tool. After successfully compiling the project and deploying it to the npm registry, I encountered an issue when importing it into my client app. Specifi ...

Removing the active class from a Bootstrap menu can be achieved by targeting the specific

I have successfully implemented a Bootstrap Menu by placing it in a separate header.html file and using the php include function to call that file on every page of my website. However, I am now trying to figure out how to dynamically change the active cl ...

Error message: Icons failing to display in conjunction with template output | 404 error code

I'm trying to display icons based on a search, but I keep getting a 404 error for http://localhost:3000/static when I input a value. My current folder structure looks like this: Root directory > Public > Icons and Root directory > index.js. ...

Selenium with Javascript

I am currently working on a website that utilizes the jquery.treeview.js plugin to display multiple nested branches. Each branch contains a JavaScript button: <a href="javascript:void(0);" id="show_link" class="show_links" onclick="$(this).parent().chi ...

Access the child element of a span by targeting a specific attribute value using Protractor

Trying to check if a popover appears using protractor. Below is the snippet of HTML code with the popover in the last child span: <span tariff-popover="views/popovers/c2g/airport.html" class="ng-isolate-scope"> <span ng-transclude=""> ...