Modifying CSS files in real-time

I've been attempting to dynamically change the CSS file, but I've run into an issue:

Whenever I try to alter the style, it seems to work correctly while in "debug mode", showing that the changes are applied. However, once the JavaScript function exits, the style reverts back to the default.

Below is the code I'm working with:

Javascript:

function checkStyle(evt) {
    var selectedStyle = evt.options[evt.selectedIndex].value;
    applyStyle(selectedStyle);
}

function applyStyle(index) {

    var cssLinkIndex = 0;
    var counter;
    switch (index) {
        case "1":
            counter = "./StyleCss/style1.css";
            break;
        case "2":
            counter = "./StyleCss/style2.css";
            break;
        case "3":
            counter = "./StyleCss/style3.css";
            break;
        case "4":
            counter = "./StyleCss/style4.css";
            break;
        default:
            counter = "./StyleCss/style1.css";
    }

    changeCSS(counter, cssLinkIndex);
}

function changeCSS(cssFile, cssLinkIndex) {

    var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);

    var newlink = document.createElement("link");
    newlink.setAttribute("rel", "stylesheet");
    newlink.setAttribute("href", cssFile);

    document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}

HTML

    <script type="text/javascript" src="./JavaScript/script.js"></script>
    <link rel="stylesheet" href="./StyleCss/style1.css">

        <div class="Menu">
            <select class="Style" onchange="checkStyle(this);">
                <option value='1' selected='selected'>Style 1</option>
                <option value='2'>Style 2</option>
                <option value='3'>Style 3</option>
                <option value='4'>Style 4</option>
            </select>
        </div>

Appreciate any assistance on this matter.

Answer №1

If you're looking to change the theme, consider using html data attributes instead of creating separate CSS files.

function switchTheme(e) {
  let theme = document.getElementById("theme-selector").value;
  let app = document.getElementById("app");
  app.setAttribute('data-theme', theme);
}
[data-theme="1"] {
  --foreground-color: #eeeeee;
  --background-color: #222222;
}

[data-theme="2"] {
  --foreground-color: #000000;
  --background-color: #eeeeee;
}

h1 {
  color: var(--foreground-color);
  background-color: var(--background-color);
}
<div id="app" data-theme="1">
  <h1>A cool title with different colors...</h1>
</div>

<select id="theme-selector" onchange="switchTheme()">
  <option value="1">Theme 1</option>
  <option value="2">Theme 2</option>
</select>

If you prefer to replace the entire file for a theme change, you can use this approach:

function switchTheme(e) {
  let themeLink = document.getElementById("theme-link");
  let theme = document.getElementById("theme-selector").value;
  if (theme === "1") {
    themeLink.href = "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css";
  } else if (theme === "2") {
    themeLink.href = "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/4.0.2/bootstrap-material-design.umd.min.js";
  }
}
<link id="theme-link" rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<h1>A cool title with different fonts...</h1>

<select id="theme-selector" onchange="switchTheme()">
  <option value="1">Theme 1</option>
  <option value="2">Theme 2</option>
</select>

You can swap between bootstrap and bootstrap material by adjusting the URLs in the code provided above.

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

Elements Fail to Display After Updating State with UseState

This question presents a challenge due to its complexity, but I will try to clarify the situation before delving into the code implementation. My aim is to create a screen for managers displaying all their drivers with minimal information and an edit butto ...

Controlling the visibility of components or elements in Angular through input modifications

Is there a more efficient way to handle button disabling and enabling based on email validation in Angular? I already have form controls set up, but want to make the process cleaner. The goal is to disable the "Get Started" button by default if the email a ...

In order to use DIV jQuery, it is necessary to have at least one input

In my form, there are 5 input fields. On button click using JQuery, I need to validate that at least one of these inputs is filled out. <div id='myForm'> <input name="baz" type="text" /> <input name="bat" type="text" /> ...

Node.js SQLite3 - DB.each() not running the subsequent code block

When running the code snippet below, I am getting the following output: var db = new sqlite3.Database("database.sqlite") console.log("2") db.each("SELECT * FROM gban WHERE id = '"+id+"'", async functi ...

What is the method of aligning content to the left side in a slick slider?

My slider is set up to display three elements, but I'm having trouble aligning one or two elements to the left instead of centering them. jQuery(function () { jQuery('.slider-blog').slick({ arrows: false, dots: true, ...

Is it possible to update parent data using a child component?

What is the correct way to update parent data using a child component? In the child component, I am directly modifying parent data through props. I'm unsure if this is the right approach. According to the Vue documentation: When the parent proper ...

React: Unexpected error occurs with invalid element type

I encountered the following issue while attempting to utilize a component Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forg ...

displaying a shadow solely on the left side of an image

When using jQuery to append an img element and apply a box-shadow on click, I am only seeing the shadow appear on the left side of the image. How can I make the box shadow show up on all sides of the image? var someNumbers = [1, 2, 3]; $.each(someNumbe ...

What is the best way to use jQuery to apply CSS only to elements with a specific attribute set?

Currently, I am attempting to utilize jQuery to apply specific CSS styles to elements, but only those that possess a particular attribute. The rationale behind not resorting solely to CSS is due to the immense amount of content on the site, making it impr ...

The button works properly in JSFiddle, however, it is not able to clear the ordered list in the

DEMO Creating a script that captures mouse click coordinates and appends them to a list. The functionality works, except for an issue with the clear button not working properly. After making corrections in jsfiddle, the script functions correctly. Howeve ...

What is the most effective approach to integrating socket.io as a submodule into the ExpressJS framework?

In my current project, I am working on developing an application using ExpressJs and following the submodule architecture recommended by tjholowaychuk. Furthermore, I also want to incorporate real-time socket interactions into the app by integrating socke ...

Proper syntax for SVG props in JSX

I have developed a small React component that primarily consists of an SVG being returned. My goal is to pass a fill color to the React component and have the SVG use this color. When calling the SVG component, I do so like this: <Icon fillColour="#f ...

The useRouter() function doesn't seem to be successfully navigating to the main landing page

"use client" import { useState } from 'react'; import {auth} from '../../firebase-config' import {createUserWithEmailAndPassword} from 'firebase/auth' import { useRouter } from 'next/router'; const SignUp = ...

Encountering a difficulty in sending data to the server through ajax with Cordova

I am currently working on a Phonegap Cordova project and I'm trying to send data to the server using AJAX but I'm encountering an error. Here is an example of my code: $(document).ready(function() { $('#frm').submit(function() ...

What is the best way to delete the pipe separator from the initial item in a list on the line?

I have a list of items separated by pipes that spans multiple lines. I am looking to use jQuery to remove the pipe separator for the first item on each line. Example: Red | Green | Blue Purple | Black | White Violet | Yellow | Magenta Here is the code ...

Tips for increasing the size of the SVG icon within Material UI iconButtons

Have you experimented with creating webpages using react.js along with the Material UI library? How can I adjust the size of an SVG icon? Recently, I developed a "create new" component, which consists of a material paper element with an add button on top. ...

What is the best way to dynamically load a view within a modal based on the clicked link?

I'm looking to optimize the loading of views inside a modal for various operations. Instead of having three separate modals, I want to dynamically load the views based on the link that is clicked. How can I achieve this? Or should I create individual ...

Is using Javascript objects a better alternative to Redux?

I'm in the process of creating my initial application with React and have opted to integrate Redux into it. Since incorporating Redux, it appears that setting a component state to a basic global JavaScript object would be a simpler approach. I unders ...

Automatically execute JavaScript upon loading the page with the option to value run on

Upon loading the page, Week 1 is automatically selected which is great. However, the javascript function only runs when I manually choose an option. I want the javascript to automatically trigger for week 1 without needing manual selection. Any ideas on ...

Discovering the page load times of web elements on a website with the help of Selenium WebDriver

On my HTML5 webpage, there are 4 charts that each take a different amount of time to load after the static content has already loaded. The loading process is indicated by a 'rendering' circle image for all 4 charts. I am looking for a way to dete ...