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

Modifying HTML tag attributes with inline server scripts

I am working with a submit button and trying to change the background color of the button itself after it has been clicked using inline server tags. <form id="form1" runat="server"> <input type="submit" id="submit" value="Submit" runat="server"/& ...

Strategies for implementing classes in Typescript

I've been working on incorporating more classes into my project, and I recently created an interface and class for a model: export interface IIndexClient { id?: number; name?: string; user_id?: number; location_id?: number; mindbody_id?: nu ...

Is there a way to dynamically adjust the height of a DIV block?

I have a situation where I need the height of one div to automatically adjust based on changes in the height of another div. var height = jQuery('#leftcol').height(); height += 20; jQuery('.rightcol-botbg').height(height); Unfortun ...

The options in the dropdown menu vanish when interacting with a jQuery feature that relies on

Recently, I have found AJAX, JSON, and jQuery to be indispensable tools in my coding endeavors. The application I am working on is a replacement for a flawed one, and it is coming along nicely. Despite making progress with the AJAX method, I have encounte ...

Node.js data transmission: Sending information from server to client

In my node project, PUG/Jade files are used to render webpages. Every minute, a JS file updates a redis database and I want the GUI to reflect these changes without requiring a page refresh. Here is an overview of how the data is currently passed: User ...

Using jQuery to handle multiple buttons with the same ID

Is there a way to address the issue of multiple buttons sharing the same id? Currently, when clicking on any button, it only updates the record with id=1. How can this problem be resolved? div id="ShowPrace"> <?php try { $stmt = $pdo->prepare(" ...

Adjusting a parameter according to the width of the browser window?

Using Masonry, I have implemented code that adjusts the columnWidth to 320 when the screen or browser window width is less than 1035px. When the width exceeds 1035px, the columnWidth should be 240. However, the current code keeps the columnWidth at 320 re ...

There is no record of the property's history

I am embarking on a fresh project utilizing React and TypeScript. One of the hurdles I have encountered is with the Router. Strangely, TypeScript does not recognize the history property, even though it should be accessible as mentioned in the documentation ...

Locate the data attribute and store it in the database using an ajax request

I am in need of a proper script to insert a data attribute into the database upon clicking using ajax. HTML: <li><a data-cat="random name">Button</a></li> jQuery: $('li a').click(function() { $(this).data('cat&a ...

AngularJS: Modifying values in one div updates data in all other divs

The webpage appears as shown below: HTML <li class="list-group-item" ng-repeat="eachData in lstRepositoryData"> <div class="ember-view"> <div class="github-connection overflow-hidden shadow-outer-1 br2"> <!-- ...

Incorporating items into a dynamic array using MobX

Issue with Pushing MobX Objects to an Observable Array I'm facing a challenge when trying to push objects into an observable array in MobX and iterate over them successfully. At the starting point, I initialize the observable array: if (!self.selec ...

Learn how to showcase a text file uploaded to a webpage with NODE js and HTML

<!DOCTYPE html> <html> <body> <form action = "/submit" method = "post"> Select a file: <input type="file" name="file"> <input type="submit"> </form> </bod ...

Utilizing MongoDB Data in an .ejs Template Using Node.js Express

After going through numerous tutorials, I find myself stuck at a point where I am struggling to render all the data written by my express-app into MongoDB in embedded JavaScript. My goal is to display this data in a simple table that always shows the updat ...

Using Angular with a hapi.js server that supports JSONP data requests

In my project, there is an endpoint specifically set at /api/profile that accepts post parameters. var http = require('http'); var serverConfig = require('../server.config.js'); var request = require('request'); module.expo ...

Utilize jQuery and AJAX to refresh functions after each AJAX call for newly added items exclusively

I have encountered an issue with my jQuery plugins on my website. Everything functions smoothly until I load new elements via AJAX call. Re-initializing all the plugins then causes chaos because some are initialized multiple times. Is there a way to only i ...

Why does pressing "enter" create a line break in HTML when typing?

Apologies in advance for what may seem like a simple CSS issue that I couldn't find an answer to on Stackoverflow. Here's the JSfiddle link: https://jsfiddle.net/kwende/fqxna79a/ In the code, you'll see two div tags: <div id="left">L ...

Removing elements from an array of objects using specific values stored in another array - JavaScript

I'm currently working on implementing a reducer in redux that can delete multiple items from the state based on an array of values. Let's say I have the following array: const idArray = ["935", "933", "930"]; My goal is to remove objects that ...

Animating sprites using TypeScript

I've been tackling the development of a small Mario game lately. However, I'm facing some difficulty when it comes to animating sprites. For instance, I have a mario.gif file featuring running Mario (although he's not actually running in th ...

node.js is reporting that it cannot locate some of the modules

Attempting to execute a file using node run index.js within the flashloan test folder results in an error that keeps occurring... node:internal/modules/cjs/loader:1042 throw err; ^ Error: Cannot find module '/home/schette/Documents/flashloan test ...

Error message: The method app.get() is invalid as it is not a

I'm having trouble using Express in a prototype function ioServer() { } module.exports = ioServer; ioServer.prototype.start = function() { var app = require('express') var http = require('http').Server(app) ...