1

for my website, I have two different CSS files. One for showing the website in a dark theme and the other one in a light theme.

Now I would like to let the user switch between the two themes. But I don't know how I could implement this. I would prefer not to create two HTML files, where the only difference is that one has a link tag to the light theme and the other one to the dark theme.

The best solution would be that the user simply clicks on a button and the theme changes without reloading.

Is this possible?

Thanks!

Edit

Decided to go with this answer. Thanks @void

atalantus
  • 721
  • 2
  • 9
  • 26
  • 1
    I would still suggest a better approach https://stackoverflow.com/a/48796000/1496715 – void Feb 14 '18 at 20:57

2 Answers2

5

Give your stylesheet link an id..

<link rel=stylesheet href=mycss.css id=shtylesheet>

Then you can change it with javascript

function changeStylesheet(newstylesheet){
    document.getElementById('shtylesheet').setAttribute('href', newstylesheet);
}

Then if you wanna do buttons or something

<button onclick="changeStylesheet('light.css')">Lights on</button>
<button onclick="changeStylesheet('dark.css')">Lights off</button>
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • Don't you think using this approach, the style transition could be abrupt. Also, it will take some time to fetch the new CSS file then the user might need to wait before he sees the transition? Check my answer here https://stackoverflow.com/a/48796000/1496715 – void Feb 14 '18 at 20:57
  • @void - that probably is a better way to do it, there are a lot of things that could be improved upon with my given approach, it's just the simplest answer i could come up with in 5 minutes.. +1 – I wrestled a bear once. Feb 14 '18 at 21:03
  • yea totally agree... – void Feb 14 '18 at 21:04
2

You can switch the theme on runtime by setting an ID to the link tag, like so:

In your HTML file:

<link type="text/css" rel="stylesheet" media="all" href="../light.css" id="theme_css" />

JS

<button onclick="switchTheme()">Switch Theme</button>

<script>
function switchTheme() {
  var check = document
  .getElementById('theme_css')
  .classList[0] === 'light';

  var element = document.getElementById('theme_css');


  if (check) {
   element.href = '../dark.css';
   element.classList.remove('light')
   element.classList.add('dark');
  } else {
   element.href = '../light.css';
   element.classList.remove('dark')
   element.classList.add('light');
  }

}
</script>

Update.

I've updated my solution to make it more dynamic. You use one button to toggle button the light and dark theme.

Facyo Kouch
  • 787
  • 8
  • 26