Updating CSS stylesheets dynamically when onchange event occurs

I am currently able to dynamically change style rules using JS, but I feel that this is limiting. I would prefer to be able to swap entire CSS stylesheet files easily. Do you have any suggestions on how to accomplish this?

Here is my code:

<label>Themes :</label>
<select name="background" id="bg" onchange="changeBg(this)">
    <option value="white">Default</option>
    <option value="#444">Dark</option>
    <option value="teal">Teal</option>
</select>

// Changing Themes
function changeBg(x){
    var body = document.getElementById('body');
    body.style.backgroundColor = x.value;
}

I also have multiple stylesheet definitions like the following:

<!-- Themes -->
    <link type="text/css" rel="stylesheet" media="all" href="style.css" id="theme1_css">
    <link type="text/css" rel="stylesheet" media="all" href="themes/dark.css" id="theme2_css">
    <link type="text/css" rel="stylesheet" media="all" href="themes/teal.css" id="theme3_css">

Answer №1

After some modifications, the JavaScript script looks like this:

// Switching Themes
function switchTheme(selectedTheme){
    var cssLink = document.getElementById('theme1_css');
    cssLink.href = 'themes/' + selectedTheme.value + '.css';
}

Special thanks to @Pete for the contribution!

Answer №2

The concept here is to utilize the disabled attribute to toggle between different themes:

<link rel="stylesheet" type="text/css" href="dark-mode.css" data-theme="dark">
<link rel="stylesheet" type="text/css" href="light-mode.css" data-theme="light">

Additionally:

function applyTheme(theme) {
    var stylesheets = document.querySelectorAll('link[rel="stylesheet"]');
    stylesheets.forEach(function(stylesheet) {
        var themeName = stylesheet.getAttribute('data-theme');
        stylesheet.disabled = themeName && themeName !== theme;
    });
}

You can now switch themes by doing something like this:

applyTheme('light');

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

Error in jQuery Ajax post request caused by a keyword in the posted data

I understand why the post is failing, but I'm at a loss on how to fix it and I haven't been able to find any solutions online. I am removing references to jEditable in an attempt to simplify things, as this issue occurs even without the jEditable ...

What is the best approach to animating a specified quantity of divs with CSS and javascript?

How neat is this code snippet: <div class="container"> <div class="box fade-in one"> look at me fade in </div> <div class="box fade-in two"> Oh hi! i can fade too! </div> <div class="box fade-in three"& ...

SVG with embedded fonts failing to display properly in web browsers

Within this SVG, there are two different font types being used: SymbolMT for the mathematical expressions and Hind-Light for the text. Both fonts have been defined within the @font-face section of the SVG. The font used for the math expressions appears a ...

discord.js fails to provide a response

const fs = require('node:fs'); const path = require('node:path'); const { Client, Collection, Events, GatewayIntentBits } = require('discord.js'); const { token } = require('./config.json'); const client = new Clien ...

Tips for generating nested elements in JSON and Java, alongside accessing the subitem values in JavaScript

By implementing this code, I was able to create the following structure int n=3; String json []= new String [n]; try { JSONArray js = new JSONArray(); ArrayList<String> ciudades; ciudades = ...

How can I make a DIV occupy the entire vertical space of the page?

I am working on a Google Maps application that takes up the majority of the screen. However, I need to reserve a strip at the top for a menu bar. How can I ensure that the map div fills the remaining vertical space without being pushed past the bottom of ...

How come the back button does not initiate client-side navigation in a Next.js application?

In my Next.js application utilizing GraphQL to fetch articles from a server, I encountered an issue with dynamic routing when reloading the page while on an article and attempting to navigate back. The usual scenario works as expected: Index -> [slu ...

What is the best way to respond to a hashchange event within AngularJs?

I am new to AngularJs and I am trying to update the page on hashchange events. Currently, I have this code which I know is not the proper way to do it: <!DOCTYPE html> <html> <head> <style> #hashdrop { display:block; ...

What is the process for uploading files using AngularFire on Firebase Storage?

Despite watching multiple videos and tutorials, I am encountering a 403 error while working with Angular 1. To solve the issue of ng-model not supporting files, I created an Angular directive named file-model: app.directive('fileModel',['$ ...

Exploring the power of Chained Promise.allSettled

Currently, I am working on a project that involves using a basic for loop to create an array of IPs for fetching. My goal is to verify that the response.status is 200 (though I have not yet implemented this), and then filter out only those IPs that return ...

How can you resize a circle in Three.js without resizing its outline?

I'm currently using a THREE.Path to generate a Circular path and then utilizing a TubeGeometry to form a circle with transparent fill and an adjustable stroke thickness. My main query revolves around the process of scaling up the Circular path dynamic ...

What is the method for obtaining the size of a mesh object in pixels (instead of Vector3) within BabylonJS?

Exploring Babylon.js How can I retrieve the size of a mesh object in pixels instead of Vector3 in a React application using Babylonjs? This is what I attempted: let meshPixelSize = meshObject.getBoundingInfo().boundingBox; ...

What is the best way to show an HTML file in a WebBrowser using C++?

Currently, I'm facing the challenge of displaying an HTML file in a WebBrowser within a Windows application. The issue lies in the fact that I am dealing with a local file instead of a URL. My attempted solution with file://MyWeb.html proved unsuccess ...

Retrieve corporate information by clicking a button with the help of jQuery

I have set up a table called company_list with the following fields: 1) Company Name 2) Country 3) Vertical Let's say there are 5 companies in this table: Company Names: Water, Earth, Sun, Moon, Star Countries: Water= UK, Earth=UK, Sun=Australia, ...

Unable to See Success Notification on First Attempt

I am facing an issue with displaying a message when adding a new record. The first time I add a record, the message shows up correctly. However, if I try to add another record, the message does not appear even though the record is added successfully. Here ...

Adjust the size of the wrapper/mask as the browser is resized

Is there a way to adjust the size of my wrapper and mask when the browser is resized? Currently, the mask stops once it's loaded, causing the content to be cut off when scrolling. You can view an example on this site. $(document).ready(function() { ...

Customizing alert message styles in Java script: Changing color and font of specific parts

I have been attempting to change a specific part of text to be bold and displayed in red color. Unfortunately, this does not seem to work on Microsoft Edge. Here is my code: alert("Hi how are you my friend"); The section that needs to be formatted: "fri ...

Is it the right time to implement a JavaScript framework?

Is there a need for using JavaScript frameworks like Angular or React if you are not developing single-page websites or components that receive live updates? ...

What is the best way to center text vertically in a <div> using CSS?

This is my first attempt at creating a chrome extension, and I am currently working on centering text. Right now, I am using text-align: centre; to align the text horizontally, but I am struggling to figure out how to align it vertically. As a result, my t ...

Refreshing a Nested Component Within a Parent Component in React

Currently, I am in the final stage of a small project where a Higher Order Component (HOC) is being utilized to display a basic Tinder-like application. The internal component is a class-based component containing its own fetch() call that presents user d ...