Load and unload stylesheets on the fly dynamically

After searching through numerous posts and forums without success, I am in need of a solution to dynamically load and unload stylesheets for my website.

The website I am constructing has a main stylesheet along with 2 optional stylesheets that alter colors. I want to have 2 links that, when clicked, will load a new stylesheet that overrides some styles from the main sheet.

For instance:

My website is yellow, which most users prefer. However, I want to give them the choice to switch to red or blue by clicking on a link. The red stylesheet will then override the main styles and turn the website red; if they click blue, it changes to blue.

To make things more complex, if a user first selects red but then changes their mind and wants blue instead, I need the red stylesheet to be unloaded and only the blue loaded.

Since I am not very knowledgeable in javascript, I am struggling with this task. Any help would be greatly appreciated!

Answer №1

How to dynamically Load CSS

var headID = document.getElementsByTagName("head")[0];
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = 'FireFox.css';
cssNode.media = 'screen';
headID.appendChild(cssNode);

Removing a CSS file dynamically

function removefile(filename, filetype) {
var targetElement = "link"; 
var targetAttr = "href"; 

var allCtrl = document.getElementsByTagName(targetElement);
for (var i=allCtrl.length; i>=0; i--)  { //Iterate backwards through the node list to find and remove matching elements
if (allCtrl[i] && allCtrl[i].getAttribute(targetAttr)!=null && allCtrl[i].getAttribute(targetAttr).indexOf(filename)!=-1);
allCtrl[i].parentNode.removeChild(allCtrl[i]);
}
}

Answer №2

After some minor adjustments, I was able to successfully implement the solution by referencing:

The link contains:

function loadjscssfile(filename, filetype){
    if (filetype=="js"){
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") 
loadjscssfile("javascript.php", "js") 
loadjscssfile("mystyle.css", "css")

function removejscssfile(filename, filetype){
    var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" 
    var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" 
    var allsuspects=document.getElementsByTagName(targetelement)
    for (var i=allsuspects.length; i>=0; i--){ 
    if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
        allsuspects[i].parentNode.removeChild(allsuspects[i]) 
    }
}

removejscssfile("somescript.js", "js") 
removejscssfile("somestyle.css", "css") 

Just a heads up: Removing a script element with this method does not unload the JavaScript code defined in it on most browsers.

Answer №3

If you are looking to update the colors of divs on your website, I recommend utilizing JQuery's ".css" function.

By using this method, you can easily modify the css properties of divs or classes with a simple click event.
To change the background color of any div with the class "class_name" to black, use the code below:

$(".class_name").css("background-color","#000000");

For further information on jQuery syntax, refer to their documentation at: http://api.jquery.com/css/

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

NodeJS async function returning a value of undefined

Hi there! I'm currently diving into the world of async functions and I seem to be running into a bit of trouble. When I use "Resolve, Reject" with Promises, everything works smoothly. However, when I attempt to implement async instead of a new Promise ...

Refresh the flatlist to display new content without uploading items automatically

When I click the save button in my FlatList component within React Native, the data does not reload automatically or render in the FlatList. However, if I manually reload the app, the saved item appears. I've tried various methods to make the data re ...

Arranging two DIVs side by side

I am struggling with positioning a promo image next to a dropdown menu, which consists of several DIVs. Currently, the image is displaying below the menu due to using inline-block and block properties in the CSS styles. .menu{ background-color: whi ...

What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions. The first function is handleFileInput: handleFileInput(event){ setTimeOut(async()=>{ let abcd= await this.convertFileToString(this.fi ...

Creating a responsive layout in HTML/CSS where the div element expands to fill the entire vertical space of its parent

Looking for assistance in creating a webpage layout like the one shown in this fiddle... http://jsfiddle.net/jeljeljel/5BSva/ I need the vertical line on the left side navigation tab to extend all the way down to the footer at the bottom of the page. Th ...

Horizontal alignment of Bootstrap columns is not working as expected

While attempting to integrate Bootstrap elements into my portfolio, I encountered issues with aligning columns. Currently, the only columns I have added are in the "welcome-section" (Lines 40-52), but they refuse to align horizontally. I've tried tro ...

When attempting to develop a discord bot using Heroku, I encounter an issue where the bot functions properly when run locally, but malfunctions once deployed on Heroku's platform

After successfully running index.js locally, I encountered an error upon trying to deploy the code on Heroku. The specific error received was: 2022-01-11T05:25:24.034595+00:00 app[worker.1]: at Module._compile (node:internal/modules/cjs/loader:1101 ...

Tips for updating multiple divs after submitting content with jQuery

My screen contains various widgets, each enclosed with different divs. Currently, I have a form that updates using AJAX when posted through jQuery. However, I am looking to refresh two additional divs located outside the form upon a single jQuery AJAX pos ...

Navigating a JSON message received from a websocket: Best practices

How can I cycle through various types of JSON messages received from WebSocket and trigger a function based on the type to modify observables in MobX? Can anyone assist with this? For instance, one of the simple messages looks like this: { name: "as ...

What is the best way to eliminate a white border around an input button in an HTML document?

.KassTv{ position: absolute; top: -213px; left: -382px; display: inline-block; background-image: url("Images/KassTv.png"); } .KassTv:hover{ background-image: url("Images/LitTv.png"); } <form action="Home.htm"> <inp ...

Is there a way for me to align my percentage with my progress bar on the same line?

I've been working on creating a UI similar to the image, but I'm struggling with positioning elements correctly. Despite trying different combinations, I can't seem to get it right. Can anyone offer some assistance? My main issue is getting ...

The CSS transition fails to function correctly once a specific function is executed

When I hover over a div, the background color changes due to a transition effect. However, if I click on a button that triggers myFunction2 to change the background color of the div before hovering over it, the transition effect no longer works. functi ...

Vuejs is throwing an error claiming that a property is undefined, even though the

I have created a Vue component that displays server connection data in a simple format: <template> <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="page-header"> < ...

What is the most effective method to ensure this layout is functioning properly?

Seeking a solution to an unexpected challenge, what initially appeared as a simple task has transformed into a complex dilemma. Balancing the vertical alignment of green DIVs while preventing absolute positioned elements from overlapping following content ...

AngularJS directive created for validation on blur

I am striving to replicate some of the features found in Angular 1.3.X for the app I am developing, with a particular focus on ensuring compatibility with IE 8. Unfortunately, this constraint means that I cannot utilize version 1.3.X. I have encountered di ...

How can Vue 3's v-bind=$attrs be implemented effectively?

I am currently in the process of migrating my Vue 2 application to Vue 3. According to the official documentation, the $listeners object has been removed in Vue 3 and event listeners are now part of $attrs. This includes taking non-prop attributes like cla ...

What is the best way to layer SQL functions in sequelize.js?

Utilizing Sequelize.JS for connecting to a MySQL database, the table structure is as follows: products --------------------- id INT name VARCHAR price DECIMAL price_special DECIMAL The goal is to retrieve the lowest price (or special_price if available) ...

What steps can be taken to issue an alert when the table does not contain any records?

Upon clicking the submit button, the value from the database is retrieved based on the hidden field ID and displayed in a table. If the value is present, it should load in the table; otherwise, an alert saying 'there is no record' should be displ ...

NodeJs: Dealing with package vulnerabilities stemming from dependent npm packages - Tips for resolving the issue

Is there a way to address npm vulnerabilities that are dependent on another package? For instance, I'm encountering an error where the undici package relies on the prismix package. Things I have attempted: Executed npm audit fix Ensured Prismix is u ...

Mystery Surrounding MP3 Playback in ASP.NET

Currently, I am utilizing an ASP.NET server side control to play MP3 files on my website. While I could utilize JavaScript or Flash controls for this purpose, the issue I'm facing is that I want the music to only play once (at the start of the site) a ...