Tips for keeping your chosen CSS style sheet consistent when moving around the site

I am currently in the process of creating my first website. I have successfully added two buttons that allow users to switch between a light theme and dark theme, with the light theme being the default. However, I am encountering an issue that I cannot seem to solve: whenever I change the theme to dark and click on another page in the menu (I have multiple HTML pages), the theme reverts back to the default one. I would like for users to be able to maintain their chosen CSS sheet throughout their entire navigation of the website. I have read that using localStorage can help achieve this, but despite trying some code snippets I found online, I have been unsuccessful in making it work. Below, I will include the HTML and JS code that I have implemented so far on my website. Please keep in mind that I am new to web programming.

HTML head section:

<link id="pagestyle" rel="stylesheet" type="text/css" href="stylesheetlight.css">

HTML body section:

<div class="themebuttons">
        <button onclick="swapStyleSheet('stylesheetlight.css')"><img src="sun.svg"></button>
        <button onclick="swapStyleSheet('stylesheetdark.css')"><img src="moon.svg"></button>
</div>

JAVASCRIPT code

function swapStyleSheet(sheet) {
  document.getElementById('pagestyle').setAttribute('href', sheet);
}

Answer №1

To ensure your code works properly, consider incorporating the localStorage feature into your swapStyleSheet function. This will allow you to save the current stylesheet each time it is updated.

Add an event listener that retrieves the saved stylesheet value from localStorage when the page loads and passes it to the swapStyleSheet function for seamless integration:

function swapStyleSheet(sheet) {
  document.getElementById('pagestyle').setAttribute('href', sheet);
  if(localStorage) localStorage.setItem("stylesheet", sheet);
}
window.addEventListener("load", e => {
  if(localStorage && localStorage.getItem("stylesheet")) swapStyleSheet(localStorage.getItem("stylesheet"));
});

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

What is the best way to position two elements inline?

I was trying to create a container named project-item that looks like the image linked below: https://i.stack.imgur.com/6XzZ9.png My goal was to align the project logo and the title (h3) in one line, but I struggled to find a suitable solution. This is ...

Update the array with the new data by setting the state

Is it possible to edit and save data in an array while iterating through it using this.state.data.map()? If so, what is the best approach to achieve this? Check out this live example for reference. Below is a sample code snippet: class App extends React ...

Is it possible to obtain the vertex coordinates of an aframe box?

Is there a way to extract the vertex from an object (specifically a box) in AFRAME, or calculate the intersection between a raycaster and an entity's face? Any assistance would be greatly appreciated. Thank you! EDIT: I have included the code snippet ...

Building a dynamic attribute management system with vue and vuetify

In the backend business object, there is a custom attributes data structure that allows clients to add key/value pairs for storing in the database. For instance: Map<String, String> customAttributes; Here's an example of how it would look in th ...

What is the best way to retrieve attributes from a through table using a query?

I am in the process of creating a straightforward shopping cart system. My structure includes a Cart model, a Product model, and a connection table called CartItems. Here are the associations: models.Cart.belongsToMany(models.Product, { through: 'Car ...

Unable to customize the appearance of the error page that pops up when JavaScript is not enabled due to restrictions on media-specific

I'm currently working on enhancing my website by adding a custom error page specifically for when javascript is disabled. I've already implemented a component within _document.js <body> <noscript> <ErrorPage /> & ...

Exploring Next.js with getServerSideProps

My code has a warning from the console attached. I would appreciate it if someone could help me identify the problem... When I use the "data" hardcoded as props, I can display them in the components, but when I try to fetch from an API, I can retrieve the ...

What could be causing my React function to be declared but not utilized?

Struggling with my React project, I hit a roadblock when trying to import my generalInput file into my App file. The error message stated that the generalInput was declared but never read. Desperate for a solution, I even turned to AI for help, but it too ...

`Open PhotoSwipe to view the image in a new window`

My goal is to open the current visible photo in a new window using JavaScript, while ensuring it works on an iPad as well. To achieve this, I added a button to the toolbar (similar to the example) and included its corresponding CSS in the photoswipe.css fi ...

Assistance with centering elements using pure CSS in responsive web design

Seeking assistance as I am facing a challenge with aligning the sponsors section on the website mentioned below. Despite implementing responsive web design, I am struggling to center the sponsors correctly. Your guidance is appreciated... ...

Is it possible to retrieve an element styled inline, such as an input?

Is it possible to style elements with inline styling using a selector such as div[style=float:right;] {}? For example: <div style="float: right;"></div> ...

The issue with Nextjs getStaticPaths is that it is not retrieving data from Firebase Firestore

I'm encountering an issue with fetching dynamic data from firestore in nextjs using getStaticPaths. While rendering the data from firestore with getStaticProps works, I'm facing a problem when trying to access specific item details as it leads me ...

Tips for utilizing the stretched-link bootstrap class while maintaining the :hover effect directly on the card

I recently customized a bootstrap product card to allow users to access the product details either by clicking on the card itself or by clicking on the product name. To achieve this, I utilized Bootstrap's stretched-link class. However, an issue arose ...

Customizing Material UI Components: Implementing the onChange Method

I've been working with the materia kit react template from creative-tim: However, I noticed that the customerInput component in this template lacks an onChange method. Does anyone have a solution for handling user inputs using this specific template? ...

What steps do I need to take in order to implement a basic ZeroClipboard copy-to-clipboard feature in jQuery on jsFiddle with just one click?

I'm having trouble implementing ZeroClipboard in a jQuery environment. My goal is to have the text within each div with the class copy copied when clicked. The following jsFiddle demonstrates the functionality with double click using the stable ZeroC ...

Troubleshoot: Firebase deployment of Vue.js application unable to locate page

I'm currently working on a silly web app with my friends for some laughs. We're using Firebase hosting and Discord OAuth2. The issue arises when attempting to access the "/login" page either by entering it in the URL or clicking "authorize" on th ...

Navigating through scenes with just a few mouse clicks and drags

I'm having an issue with TrackballControls. It's not functioning properly and I can't figure out why. I'm following the example provided here: link to example. I've been searching for a solution but still can't seem to pinpoin ...

AngularJS Search Filtering Error: [ng:areq]

Trying to implement a search filter in my AngularJS application, but encountering an error in the Chrome console: Error: [ng:areq] Below is the code snippet: <div id="notebooks" ng-controller="NotebookListCtrl"> <input type="text" id="query" n ...

Are you having trouble grasping JavaScript concepts?

Can Javascript replicate Smalltalk's doesNotUnderstand or Ruby's method_missing functionality? ...

React-router Link failing to load content

In my current development setup, I am utilizing React and Rails with AWS S3 to create a platform similar to YouTube. I've encountered an issue with navigating to different video content within a watch page using react-router. When clicking on a link t ...