Can the CSS styles of a webpage be modified post-page load?

Hello there! I've been working on implementing a "dark mode/light mode" feature for my website. My approach involves using two different CSS style sheets and toggling between them using a single button

So far, I've experimented with various methods like setAttribute, innerHTML, and removeAtribute to achieve this functionality. I even tried moving the contents of one style sheet into <style> tags but couldn't get it to work as intended.

Switch to Light Mode

function light(){

    document.getElementById("css").setAttribute("href", "LIGHTMODE.CSS")
    document.getElementById("darkmode").innerHTML = "Switch to Light Mode"
    document.getElementById("darkmode").onclick = "dark()"
}

function dark(){
    document.getElementById("css").setAttribute("href", "DARKMODE.CSS")
    document.getElementById("darkmode").innerHTML = "Switch to Dark Mode"
    document.getElementById("darkmode").onclick = "light()"
}

The goal is to identify the elements by their IDs and dynamically change the href attribute based on user interaction

Answer №1

You have the ability to load both stylesheets and toggle between them whenever you need.

<link rel="stylesheet" href="darkmode.css" class="css dark">
<link rel="stylesheet" href="lightmode.css" class="css light" disabled>

<script>
    function setMode(mode) {
        document.querySelectorAll('link.css').forEach(sheet => {
            sheet.disabled = !sheet.classList.contains(mode);
        })
    }
    setMode('dark');
    setMode('light');
</script>

Upon loading the page, the light stylesheet is initially disabled.

The advantage of this approach is that even though the stylesheet is disabled, it is still loaded during page initialization. This results in an instant switch between styles without any delay caused by loading CSS for the other style.

Answer №2

Simply inserting the href into an existing element won't trigger the browser to fetch the new CSS automatically.

Also, it seems that both your dark and light functions are utilizing the same CSS file called LIGHTMODE.CSS. Consider using DARKMODE.CSS within the dark function instead.

function dark(){
    // Locate the HTML head element
    var head = document.getElementsByTagName('HEAD')[0];

    // Create a new link Element
    var link = document.createElement('link');

    // Set the attributes for the link element
    link.rel = 'stylesheet';

    link.type = 'text/css';

    link.href = 'DARKMODE.CSS';

    // Append the link element to the HTML head
    head.appendChild(link);
}

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

Best Method for Updating a Single Scope and Setting the Others to False in AngularJS

If I have 4 fields in my view that need to be toggled open or closed when clicked, with the requirement of closing the other three, how can this be achieved without duplicate code? <div class="square red"></div> <div class="square blue"> ...

Updating ngModel using the value retrieved from a service call

After experiencing dissatisfaction with Angular's form validation, I decided to develop my own solution. However, I have encountered a perplexing issue that has me at a loss. Here is how my setup looks: I employ a directive to create a new form. Th ...

The data retrieved using Ionic 3 Angular Fire's payload.val() seems to be returning

Is it possible to determine whether a profile is filled in or empty when using Firebase Database for storing profile information? Currently, I am utilizing profile.payload.val(), but it seems to return null in both cases instead of true when the profile is ...

How to achieve a seamless iframe effect using CSS

With the introduction of new HTML5 iframe attributes, there are now more options available. One such attribute is the seamless attribute, which has the ability to: Create an iframe that appears to be seamlessly integrated into the containing document. ...

After repeated attempts to initialize and destroy, Froala encounters issues when loading a textarea via Ajax

Whenever an EDIT button is clicked to update some Blog Data, it triggers an Ajax call that brings up a textarea for Froala and initiates the initialization process. This sequence works smoothly initially, but after a few cycles of edit/submit (1, 2, or 3 o ...

How can one make the image pop and stand out from its background?

I am trying to achieve a similar effect as shown in this design where the image stands out from its background. I have managed to do that, but I am struggling with aligning the image to the center and bottom with overflow. Can anyone help me with this? Th ...

The Three.js raycaster fails to intersect with objects once they have been displaced from their original position

I am encountering an issue with the raycaster: When I place an object at the origin (0, 0, 0), the raycaster can detect it. However, if I move the object to a different position, like (0, 300, 0), the raycaster no longer hits the object. I have double-ch ...

Set the value of a variable to the result of a JavaScript function

I recently wrote a function that retrieves JSON data from a specified URL. Here's what the function looks like: function getJSON(url) { request.get({ url: url, json: true, headers: { 'User-Agent': 'request&a ...

What are some ways to reuse an angular component multiple times?

I am utilizing an angular component to dynamically load charts into my widget: Below is an example of the component: angular.module("generalApp").component("chartPie", { template: "<div class=Pie></div>", bindings: { data: "=", }, control ...

Is there a way to transform a fixed parameter into a user input value and display the function's outcome on a different page?

I am in the process of developing a straightforward web application for book searching based on ISBN. The website will feature a text input field for entering an ISBN and a submit button. Essentially, a user can enter an ISBN in the designated box, click s ...

Having trouble binding form data to a React component with the onChange() method?

I've been working on developing an email platform exclusively for myself and encountered a roadblock with this React form not updating state when data is entered. After identifying the issue, it appears that the main problem lies in the React form not ...

"Utilizing Bootstrap to create a space-saving table layout with an

Using Bootstrap on a table causes an unexpected empty column to appear on the right side (as shown in the screenshot). This issue is strange because it works fine with another table using the same setup... but this particular table seems to have a mind of ...

Can RethinkDB and Node.js/Express handle parallel queries with multiple connections?

Is there a more efficient method for running parallel queries with the RethinkDB Node driver without opening multiple connections per request? Or is this current approach sufficient for my needs? I'd like to avoid using connection pools or third-party ...

programming / mathematics - incorrect circular item rotation

I need help arranging a sequence of planes in a circular formation, all facing toward the center. However, I seem to be experiencing issues with the rotation after crossing the 180-degree mark. While my objects are correctly positioned around the circle, t ...

Issue with displaying a vTable component in VueJS / Vuetify

I am struggling with this basic HTML/Vue/Vuetify code snippet below, and I can't seem to get it functioning as intended. const { createApp, computed, ref, reactive } = Vue; const { createVuetify } = Vuetify; const ...

Having trouble executing an npm script - getting an error message that reads "Error: spawn node_modules/webpack/bin/webpack.js EACCES"

After installing and configuring Linux Mint, I encountered an error when trying to run my project with the npm run dev command. The error message "spawn node_modules / webpack / bin / webpack.js EACCES" keeps appearing. I have attempted various methods fo ...

Modify the CSS color attribute interactively by clicking

I have a function that can generate random colors. I would like to utilize this function along with jQuery's toggleClass feature to change the color of a table cell when clicked, and revert it back to its original color if clicked again. Here is the ...

Alter the hue of the div

Having trouble with this code snippet: function red(opt) { var sqr; sqr="r"+parseInt(opt); hilight_css = {"background-color":"#f00"}; $(#sqr).css(hilight_css); } I am calling the function like so: red(questions); The variable question ...

Generate a .py file through an HTML button click and save it to your device

My current project involves developing HTML and JavaScript code for a chatbot. I need to implement a feature where, upon receiving a Python program from the chatbot, a download button should be displayed. When users click on this Download button, they shou ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...