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!
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>
Just check and change the style using a ternary operator:
function dark_mode() {
document.body.style.background = document.body.style.background == "#2C2F33" ? "#FFFFFF" : "#2C2F33";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With