Home > OS >  button change css style at switch to dark / lightmode
button change css style at switch to dark / lightmode

Time:11-21

old (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.)

new (now the button change style is missing when you click on it)

function myFunction() {
   var element = document.page;
   element.classList.toggle("dark-mode");
}
<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>


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

CodePudding user response:

I don't believe document.page is valid js. assign the class to body

document.getElementsByTagName('button')[0].textContent='dark-mode';
function myFunction() {
   var element = document.getElementsByTagName('body')[0];   
   element.classList.toggle("dark-mode");
   
   var button = document.getElementsByTagName('button')[0];
   if(button.textContent == 'dark-mode')button.textContent='white-mode';
   else button.textContent='dark-mode';
}
<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()"></button>


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

  • Related