-2

How can I allow the user to switch to page dark theme without using any third-party libraries? (This question answers provide only external libraries, but I want to do it without them.)

jiwopene
  • 3,077
  • 17
  • 30

2 Answers2

1
:root {
    --bg-color: #cfd8dc;
    --text-color: #212121;
}

[data-theme="dark"] {
    --bg-color: #263238;
    --text-color: #e0e0e0;
}

body {
  color: var(--text-color);
  background-color: var(--bg-color); 
  font-family: "Playfair Display";
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}

.toggle-button {
  -webkit-appearance: none;
  outline: none;
  width: 200px;
  height: 100px;
  background-color: #212121;
  border-radius: 50px;
  position: relative;
  transition: .4s;
}

.toggle-button:before{
  content: "";
  position: absolute;
  height: 100px;
  width: 100px;
  border-radius: 50px;
  top: 0;
  bottom: 0;
  background-color: #bdbdbd;
  transition: .4s;
}

.toggle-button:checked {
  background-color: #bdbdbd;
}

.toggle-button:checked:before {
  transform: translate(100%);
  background-color: #212121;
  transition: .4s;
}

<script>
const toggleSwitch = document.querySelector('.toggle-button');

function switchTheme(e) {
  if(e.target.checked) {
    document.documentElement.setAttribute('data-theme', 'dark');
  } else {
    document.documentElement.setAttribute('data-theme', 'light');
  }
}

toggleSwitch.addEventListener('change', switchTheme, false);
</script>

<nav>
  <h1>Light Theme/Dark Theme Selector</h1>
</nav>
<div class="container">
  <h2 style="margin-right:20px">Light</h2>
  <input type="checkbox" class="toggle-button">
  <h2 style="margin-left:20px;">Dark</h2>
</div>
0

If you want it to allow two designs of the web, use HTML class on html node:

function makeDark() {
  document.body.parentNode.classList.remove("light")
  document.body.parentNode.classList.add("dark")
}

function makeLight() {
  document.body.parentNode.classList.add("light")
  document.body.parentNode.classList.remove("dark")
}
.dark {
  color: #fff;
  background: #012;
}

.light {
  color: #000;
  background: #def;
}

.dark input {
  appearance: none;
  background: #000;
  color: #fff;
}
<!doctype html>
<html class="dark" lang="en">

<head>
  <meta charset=utf8>
  <title>Foo</title>
</head>

<body>
  <p>Some text</p>

  <input value=input text>

  <button onclick=makeDark()>Dark</button>
  <button onclick=makeLight()>Light</button>
</body>

</html>

You then would also want to store the status in a cookie.

jiwopene
  • 3,077
  • 17
  • 30
  • Some operating systems (in combination with some browser versions) provide information about the currently set theme. It should be reflected by the page. – jiwopene Mar 14 '22 at 15:46