0

I added a theme in my HTML page by:

<link rel="alternate stylesheet" href="css/dark.css" title="dark">

this creates an option to switch theme from view>style in browser as it is expected to. I want to create a switch in the page itself for changing the theme. <button>Switch Theme</button>will create a button but how do I make it switch theme?

Sid
  • 17
  • 1
  • 5
  • Which browsers have that option? – Mrigank Pawagi Jan 13 '18 at 15:14
  • 2
    Use javascript to bind a click event to the button, on click have the function toggle a `body` class, e.g `` - use this class as a base selector for applicable theme styles, e.g: `.dark a {color: white;}` and `.light a {color: black;}`, etc. – UncaughtTypeError Jan 13 '18 at 15:15
  • 2
    Possible duplicate of [Replacing css file on the fly (and apply the new style to the page)](https://stackoverflow.com/questions/19844545/replacing-css-file-on-the-fly-and-apply-the-new-style-to-the-page) – Temani Afif Jan 13 '18 at 15:25

2 Answers2

4

You should trigger a change in the href attribute of the <link> tag on the click of the button, as demonstrated:

HTML

<link rel="stylesheet" href="dark.css" id="theme">
<button id="switch">Switch Theme</button>

JavaScript

document.getElementById('switch').onclick = function() {
  if (document.getElementById('theme').href == "dark.css") {
    document.getElementById('theme').href = "light.css";
  } else {
    document.getElementById('theme').href = "dark.css";
  }
};

Now, the dark.css and light.css would contain different styles for your elements for both the themes respectively. For example:

dark.css

body{
    background: #000;
}

light.css

body{
    background: #fff;
}
Mrigank Pawagi
  • 892
  • 1
  • 8
  • 26
0

this is very simple you need to bind the click to function and call it:

Replacing css file on the fly (and apply the new style to the page)

Vitaly Menchikovsky
  • 7,684
  • 17
  • 57
  • 89