Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to revert changes to css made by javascript

So I have a button that toggles a simple dark theme for my web app.

<button class="btn btn-primary" onclick="dark_mode()">Dark Mode ON</button>

Once the user clicks it will activate this function in javascript.

function dark_mode() {
    document.body.style.background = "#2C2F33";}

This will only change the background. I am wondering if the user clicks the button a second time it will revert the changes made by the function. (i.e toggle on/off) Thanks for the time and help in advance!

like image 936
Keegan Husom Avatar asked Dec 14 '22 12:12

Keegan Husom


2 Answers

You can make it by toggling CSS class, it is more flexible solution

function dark_mode() {
  document.body.classList.toggle('dark-mode')
}
.dark-mode {
  background: #2C2F33
 }
<button class="btn btn-primary" onclick="dark_mode()">Dark Mode ON</button>
like image 67
Kirill Avatar answered Dec 18 '22 00:12

Kirill


Just check and change the style using a ternary operator:

function dark_mode() {
    document.body.style.background = document.body.style.background == "#2C2F33" ? "#FFFFFF" : "#2C2F33";
}
like image 34
Jack Bashford Avatar answered Dec 18 '22 00:12

Jack Bashford