A cookie designed to store and retain the preferred CSS stylesheet choice

I'm looking to create a cookie that will store the preference for a specific CSS stylesheet. I currently have a function in place that allows me to switch between stylesheets:

function swapStylesheet(sheet){

    document.getElementById('pagestyle').setAttribute('href', sheet);

}

This function is called from buttons like so:

<a button class="Button" onclick="swapStylesheet('DayStyle.css')">Light</a>
        
<a button class="Button" onclick="swapStylesheet('NightStyle.css')">Dark</a>

However, I've noticed that the href reverts back to the default stylesheet upon refreshing the page. Is there a way to implement a cookie that remembers the preferred stylesheet? And can this cookie be applied site-wide?

Answer №1

If you want to save user preferences for styling on your website, one option is to utilize the localStorage feature in your browser. Cookies are typically used for server-side data reading, but cookies can still be used if desired.

Another alternative is sessionStorage, but keep in mind that the preferred theme will not persist once the tab or browser is closed as sessionStorage does not retain data after the session ends. This could defeat the purpose of remembering a user's preference.

Here's an approach using localStorage:

After the user selects a style, you can implement a function like this:

function swapStylesheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
    localStorage.setItem('stylesheet', sheet);
}

To apply the saved style when the page loads, you can use the

<body onLoad ="checkLS()">
function:

function checkLS () {
    let sheet = localStorage.getItem('stylesheet');
    if (sheet) {
        swapStylesheet(sheet);
    }
}

This method ensures that the user's preferred stylesheet/theme is automatically applied even if the browser was closed between visits.

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

Attempting to reach <p> from numerous web pages

Currently, I am working on a project where I need to extract text data from various websites. I have successfully managed to retrieve the text data using <p> tags. I would really appreciate any assistance with this task. Thank you! ...

What methods can be used to maintain the selected date when the month or year is changed in the react-datepicker component of reactjs?

At the moment, I am using the Month selector and Year selector for Date of Birth in the react-datepicker component within a guest details form. The current functionality is such that the selected date is highlighted on the calendar, which works fine. How ...

Leveraging ES6 Generators for Efficient XMLHttpRequests

My goal is to simplify AJAX calls using ES6 generators, but I've encountered some issues: let xhr = new XMLHttpRequest() function *statechange() { yield xhr.readyState; } let gen = statechange(); xhr.open("GET", myUrl, true); xhr.onreadystatec ...

Discovering the magic of activating a JavaScript function on jQuery hover

I need to call a JavaScript function when hovering over an li element. var Divhtml='<div>hover</div>'; $('li a').hover(function(){ $(this).html(Divhtml); //I want to trigger hovercall(); wh ...

How can one HTML form be used to request a unique identifier from the user, retrieve a record from the database, parse it into JSON format, and then populate an HTML page form using the

As someone who isn't an expert in any specific coding language, I have a knack for piecing things together to make them work. However, my current challenge is stretching my technical abilities a bit too far. Here's what I'm trying to achieve ...

Tips on incorporating the authorization header in the $.post() method with Javascript

When attempting to POST data to the server, I need to include an Authorization header. I attempted to achieve this using: $.ajax({ url : <ServiceURL>, data : JSON.stringify(JSonData), type : 'POST', contentType : "text/html", ...

Attempting to bring in HTML through a helper, but Rails doesn't seem too thrilled about it

I have a form that triggers a remote GET request, leading to the display of a modal. The issue I'm facing is that multiple actions can utilize the same model, so I am attempting to employ a helper and jQuery to showcase different data based on what is ...

Using a JavaScript script in my HTML alongside Vue.js is not possible

Hello there! I recently created a Node.js server and now I'm trying to display an HTML file that contains a Vue script which loads data using another method written in a separate JS file. However, when I attempt to load my HTML file in the browser, ...

Issue with Node.js Stream - Repeated attempts to call stream functions on the same file are not being successful

When a POST request with multipart/form-data hits my server, I extract the file contents from the request. The file is read using streams, passed to cvsParser, then to a custom Transform function that fetches the resource via http (utilizing got) and comp ...

What is the optimal strategy for managing multilingual text in a React website?

As I develop a react website with multiple localizations, I am faced with the question of how to best store UI texts for different languages. Currently, I am contemplating two approaches: One option is to store text directly in the UI code, using an objec ...

What is the best method for verifying that audio has not been loaded correctly?

After creating a script to scrape for mp3 audio file URLs and load them into my HTML audio element's src, I encountered an issue where some of the URLs were not functioning properly. As a result, the audio was unable to execute the load() method since ...

AWS Lambda, where the billing time exceeds the actual processing time

While working on my Lambda function in Node.js, I noticed a significant difference in the time measured from the start to the end of the function compared to the billed duration provided by Lambda. The function itself takes around 1400 milliseconds to exec ...

Do all descendants consistently trigger rerenders?

Recently, I was exploring the React new documentation here, where I came across this interesting piece of information: The context value mentioned here is a JavaScript object with two properties, one being a function. Whenever MyApp re-renders (for examp ...

Press on the button that is currently in your field of view

I have a web page with multiple buttons inside div elements. I am looking to automate the process of clicking the "Buy" button that is currently visible on the screen when the user presses the B key. $(document).keydown(function(e) { if (e.keyCode == ...

Acquiring the item by referencing one of its property's values

Imagine you have a JSON structure that looks like this: [ { "name":"Foo" "nickname":"Lorem Ipsum" }, { "name":"Bar" "nickname":"Dolor S ...

Bug on a Safari browser when using a dotted border on a table

Issue in Safari and Chrome browsers: CSS: TABLE { width: 100%; clear: both; border: 0px; border-collapse: collapse; } TABLE TH, TABLE TD { padding: 10px; text-align: center; border: 1px dotted #898989; } ...

The dropdown within the modal is proving elusive for Selenium to locate

I am attempting to choose a value from the dropdown menu labeled 'ddl_settpymtaction' using Selenium, but unfortunately it seems to be unable to locate it within the modal where it is located. CSS: https://i.stack.imgur.com/3YWQu.png Selenium ...

Tips on adjusting the SVG view box for optimal visibility in a web browser

Recently, I've encountered an issue with the following code snippet: d3.xml("https://crossorigin.me/https://svgshare.com/i/5w9.svg").mimeType("image/svg+xml").get(function(error, xml) { if (error) throw error; document.body.appendChild(xml.docume ...

What type of technology is typically utilized in creating functional platforms such as goDaddy, wix, and other web design websites?

I am currently working on a web development project that aims to allow users to edit webpages without needing any coding knowledge. Users with authorization will be able to modify not only the text but also various HTML tags on the page, similar to platfor ...

reversed json using javascript

Is it possible to efficiently reverse the order of the following JSON object: { "10": "..." "11": "...", "12": "...", "13": "...", "14": "...", } so that it becomes: { "14": "...", "13": "...", "12": "...", "11": "... ...