Reputation: 13
I am trying to add a "dark mode/light mode". I am trying to do this by using two different CSS style sheets and having a single button to click through them
ive tried using setAttribute, innerHTML, removeAtribute( moving the contents of one style sheet into tags and trying to remove one stylesheet)
change to Light Mode
function light(){
document.getElementById(css).setAttribute("href", "LIGHTMODE.CSS")
document.getElementById(darkmode).innerHTML="Change to Light Mode"
document.getElementById(darkmode).onclick="dark()"
cos
}
function dark(){
document.getElementById(css).href = "LIGHTMODE.CSS"
document.getElementById(darkmode).innerHTML="Change to Dark Mode"
document.getElementById(darkmode).onclick ="light()"
console.log(darkmode)
}
It should identify the throught the Id and change the href to whatever is stated
Upvotes: 0
Views: 1405
Reputation: 1
You can have both stylesheets loaded, and enable/disable them at will
<link rel="stylesheet" href="darkmode.css" class="css dark">
<link rel="stylesheet" href="lightmode.css" class="css light" disabled>
<script>
function setcssmode(s) {
document.querySelectorAll('link.css').forEach(ss => {
ss.disabled = !ss.classList.contains(s);
})
}
setcssmode('dark');
setcssmode('light');
</script>
In this example, the light stylesheet is disabled on page load.
The benefits of doing it this way is that the stylesheet that is disabled is still loaded on page load, therefore the switch will be instantaneous, rather than potentially delayed while the CSS for the alternative style is loading
Upvotes: 2
Reputation: 9592
If you just add href
to an existing element, browser would not automatically fetch the new CSS.
By the way, both your dark
and light
function are using same CSS namely LIGHTMODE.CSS
, maybe you want to use DARKMODE.CSS
inside dark
function dark(){
// Get HTML head element
var head = document.getElementsByTagName('HEAD')[0];
// Create new link Element
var link = document.createElement('link');
// set the attributes for link element
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'DARKMODE.CSS';
// Append link element to HTML head
head.appendChild(link);
}
Upvotes: 0