Suppose I have 2 stylesheets, dark.css and light.css . I want to allow the user to switch between these two themes in the homepage and set it as default to other pages too. My website also contains many other css files which are almost same for both themes( otherwise it would be a problem!!)
Asked
Active
Viewed 1,235 times
0
-
See: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet#Notes, then try something and come back. – Randy Casburn Mar 02 '19 at 13:52
1 Answers
0
We should never switch or unload css
file in order to do such things. It is better to switch a class in html
or body
element.
For example -
First of all load both css
style file. Then for dark.css
, wrap all your styles under root class dark
just like below -
.dark .style1{
...
}
.dark .style2{
...
}
Same for light.css
.light .style1{
...
}
.light .style2{
...
}
And then switch the class of body
tag using below JavaScript -
<button id="dark">Dark theme</button>
<button id="light">Light theme</button>
let body = document.body;
let darkBtn = document.getElementById('dark');
let lightBtn = document.getElementById('light');
darkBtn.addEventListener('click', () => {
body.classList.remove('light');
body.classList.add('dark');
});
lightBtn.addEventListener('click', () => {
body.classList.remove('dark');
body.classList.add('light');
});
Live in action - https://jsitor.com/3xKxgP8Ow

Ashvin777
- 1,446
- 13
- 19