Home > front end >  Dark mode and light mode html, css, javascript how?
Dark mode and light mode html, css, javascript how?

Time:11-20

Hello and thank you in advance, I would like to make a button with darkmode and if you click on it then it becomes darkmode and the button is then called white mode then when you click on it again it becomes white mode and the button is called dark mode again.

Code:

<!DOCTYPE html> 
<html>
<head>
<style>
.page {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}
</style>
</head>
<body>

<div class="page">Hello</div>

<button onclick="myFunction()">dark mode</button>

<script>
function myFunction() {
   var element = document.page;
   element.classList.toggle("dark-mode");
}
</script>

</body>
</html>

CodePudding user response:

You are trying to toggle the dark-mode class on document.page, which doesn't exist.

Instead, you should be toggling it on document.body.

<!DOCTYPE html> 
<html>
<head>
<style>
.page {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}
</style>
</head>
<body>

<div class="page">Hello</div>

<button onclick="myFunction()">dark mode</button>

<script>
function myFunction() {
   var element = document.body;
   element.classList.toggle("dark-mode");
}
</script>

</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

To only toggle the class on the div, use querySelector:

<!DOCTYPE html> 
<html>
<head>
<style>
.page {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}
</style>
</head>
<body>

<div class="page">Hello</div>

<button onclick="myFunction()">dark mode</button>

<script>
function myFunction() {
   var element = document.querySelector('div.page');
   element.classList.toggle("dark-mode");
}
</script>

</body>
</html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

function myFunction() {
   var element = document.body;
   element.classList.toggle("dark-mode");
   if (element.classList.contains("dark-mode")){
    document.getElementById('btn').innerHTML = "Light Mode";
   }
   else{
    document.getElementById('btn').innerHTML = "Dark Mode";
   }
}
.page {
  display:inline;
  background:#FFF;
  color: #121212;
  font-size: 25px;
}

.dark-mode,
.dark-mode .page {
  background-color:#202020;
  color: #FFF;
}
<!DOCTYPE html> 
<html>
<head>
</head>
<body>
<div class="page">Hello</div>
<br><br><br>
<button onclick="myFunction()" id="btn">Dark mode</button>
</body>
</html>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related