skip to Main Content

The input checkbox toggles between light/dark mode. However, I want it as 2 separate buttons. How do I go about this?

Demo: https://jsfiddle.net/ot1ecnxz/1

HTML:

<input type="checkbox" role="switch" id="flexSwitchCheckChecked" checked onclick="myFunction()" />
<hr />
<button type="button" data-bs-theme-value="light"> Light </button>
<button type="button" data-bs-theme-value="dark"> Dark </button>
<hr />
<p>
This is a sample text
</p>

JS:

function myFunction() {
    var element = document.body;
  element.dataset.bsTheme =
  element.dataset.bsTheme == "dark" ? "light" : "dark";
}

2

Answers


  1. If checkbox replaced by 2 dedicated buttons code to achieve this should be,

    HTML :

    <button type="button" data-bs-theme-value="light" onclick="setTheme('light')"> Light </button>
    <button type="button" data-bs-theme-value="dark" onclick="setTheme('dark')"> Dark </button>
    <hr />
    <p>
        This is a sample text
    </p>
    
    

    Javascript:

    function setTheme(theme) {
        document.body.dataset.bsTheme = theme;
    }
    
    Login or Signup to reply.
  2. Html

    <button type="button" onclick="setTheme('light')">Light</button>
    <button type="button" onclick="setTheme('dark')">Dark</button>
    

    JS

    function setTheme(theme) {
       var element = document.body;
       element.dataset.bsTheme = theme;
    }
    

    try for this code

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search