How to use Two Toggle buttons on same page having same function with different css?

Related searches

I have been trying to hard to add 2 Toggle Buttons having different styles (css) on Menu Bar and footer page. They are to be used for night and dark mode.

However when I use

onclick="themeToggle()" id="theme-switcher" 

for both of the buttons, only one of them works.

This is my Toggle Buttons Test Page.

This is the js which is being used :

 var tSwitcher = document.getElementById('theme-switcher');
let element = document.body;

 let onpageLoad = localStorage.getItem("theme") || "";
 if(onpageLoad != null && onpageLoad  == 'dark-mode'){
      tSwitcher.checked = true;
 } 
 element.classList.add(onpageLoad);


function themeToggle(){
      if(tSwitcher.checked){
          localStorage.setItem('theme', 'dark-mode');
            element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
            element.classList.remove('dark-mode');
        }
    }

This is the code for Two Toggle buttons

    <label class="switcher">
    <input type="checkbox" onclick="themeToggle()" id="theme-switcher">
    <div>
    <i class="fas fa-sun"></i>
    <i class="fas fa-arrow-left arrow"></i>
    <i class="fas fa-moon"></i>
    </div>
    </label> 

 <label class="switch" style="padding: 23px 0;">
<input type="checkbox" onclick="themeToggle()" id="theme-switcher">
<div>
    <span></span>
</div>

Kindly help me in solving the issue with the code as well.

Thanks for the help.


Because you are using ID in <input type="checkbox" onclick="themeToggle()" id="theme-switcher">, which you repeat in other checkbox. so only first ID in the DOM will be taken.

Change your <input type="checkbox" onclick="themeToggle()" id="theme-switcher">

To

<input type="checkbox" onclick="themeToggle()" class="theme-switcher">

And update the below code

Note: dont repeat ID

var tSwitcher = document.getElementsByClassName('theme-switcher');
let element = document.body;

let onpageLoad = localStorage.getItem("theme") || "";
if (onpageLoad != null && onpageLoad == 'dark-mode') {
        for(let i = 0; i<tSwitcher.length; i++){
                tSwitcher[i].checked = true;    
    }

}

if(onpageLoad) element.classList.add(onpageLoad);

So update your themeToggle() to

  function themeToggle() {
    if (event.target.checked) {
      localStorage.setItem('theme', 'dark-mode');
      element.classList.add('dark-mode');
    } else {
      localStorage.setItem('theme', '');
      element.classList.remove('dark-mode');
    }
  }

How to click a button from multiple buttons on same page in , Why your attempts failed: your first attempt: WebElement button = driver. findElements(By.cssSelector("button[@class='button' and @type� Cascading Style Sheets provide webmasters a lot of control over their websites' appearance. One of its features is that you can specify different or alternate style sheets for a page. If your visitor prefers a particular design, or theme, that person can simply switch to that theme using their browser.


If you are using getElementById it will return the first occurrence of that id from dom, and as you are having same id on both button it is updating the first button every time. Instead, you can except event object, in click function, and assign event.target to get the button element.

A Complete Guide to Links and Buttons, You can use multiple space-separated values if you need to (e.g. Indicates that its destination represents the same person or entity as the current page. addEventListener("beforeunload", function(event) { // Remind user to save the button will have a button class and handles a toggle-like active class. Using the above approach also gives you the added benefit of SEO/unique URLs. To reiterate my point, yes, I won’t argue that you need various UI components to achieve certain results, but specifically having multiple submit buttons as part of the same form is not a good idea … IMO.


You can't use the same ID for two or more HTML elements. Also, once you want to use this functionality in multiple elements, I strongly recommend you to not use onclick inline. Instead, you can get all switchers from your page and add a listener to them:

Get all switchers in your page
const switchers = document.querySelectorAll('.switcher');
Apply the click event listener on them
switchers.forEach((element) => {
    element.addEventListener('click', (event) => {
        themeToggle(event);
    });
});
Finally, you must add the switcher class to all elements
<input type="checkbox" id="theme-switcher-1" class="switcher">
<input type="checkbox" id="theme-switcher-2" class="switcher">
<input type="checkbox" id="theme-switcher-3" class="switcher">

Using this approach, you can use this method all over your website or application and it's also easier to maintain.

Update: you should adjust the themeToggle() method like so:

function themeToggle(event){
  var tSwitcher = event.target;
  if(tSwitcher.checked){
    localStorage.setItem('theme', 'dark-mode');
    tSwitcher.classList.add('dark-mode'); // changed element to tSwitcher
    console.log('Dark mode is on');
  } else {
    localStorage.setItem('theme', '');
    tSwitcher.classList.remove('dark-mode'); // changed element to tSwitcher
    console.log('Dark mode is off');
  }
}
Example snippet

Obs.: You should adjust it into your code. I had to comment localStorage because it didn't work here.

const switchers = document.querySelectorAll('.switcher');
console.log(switchers);
switchers.forEach((element) => {
    element.addEventListener('click', (event) => {
        themeToggle(event);
    });
});
function themeToggle(event){
  var tSwitcher = event.target;
  if(tSwitcher.checked){
    //localStorage.setItem('theme', 'dark-mode');
    tSwitcher.classList.add('dark-mode');
    console.log('Dark mode is ON on ' + tSwitcher.id);
  } else {
    //localStorage.setItem('theme', '');
    tSwitcher.classList.remove('dark-mode');
    console.log('Dark mode is OFF on ' + tSwitcher.id);
  }
}
<input type="checkbox" id="theme-switcher-1" class="switcher"><br />
<input type="checkbox" id="theme-switcher-2" class="switcher"><br />
<input type="checkbox" id="theme-switcher-3" class="switcher">

How To Toggle Between Class Names, Icon Bar Menu Icon Accordion Tabs Vertical Tabs Tab Headers Full Page Tabs Hover Tabs Toggle between adding and removing a class name from an element with JavaScript. to the div element with id="myDIV" (in this example we use a button to toggle the class name). Step 2) Add CSS: function myFunction() { To create multiple buttons having different functioanlities in an HTML page is an easy job. Try following the bolow easy steps-Create multiple buttons(as many as you want). Add the attribute onclick="" for all the buttons . Write down the name of the function inside the double quotes in onclick="". Make sure not to forget opening and closing circular brackets after function name like this- > ()


First of all, you cannot have two or more elements with the same id.

To detect what button is being clicked you can pass the event to the function as argument like this.

onclick="themeToggle(event)" class="switcher" id="theme-switcher-2"

Once you have the event you can get the object that has fired it (In your case the button) like this.

    function themeToggle(event){
          var tSwitcher = event.target;
          if(tSwitcher.checked){
              localStorage.setItem('theme', 'dark-mode');
                element.classList.add('dark-mode');
            } else {
              localStorage.setItem('theme', '');
                element.classList.remove('dark-mode');
            }
    }

EDIT

To set the default behaviour properly you have to add class="switcher" to each button and do this.

var tSwitchers = document.querySelectorAll('.switcher'));
let onpageLoad = localStorage.getItem("theme") || "";
tSwitchers.forEach((element) => {
    if(onpageLoad != null && onpageLoad  == 'dark-mode'){
       element.checked = true;
    } 
});

How To Toggle Text, of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML. Border Nav Links Right Aligned Menu Links Centered Menu Link Equal Width Learn how to toggle text with JavaScript. <button onclick="myFunction ()">Click Me</button> Step 2) Add JavaScript: Example. function myFunction() { Updated: March 15, 2019 to use Flexbox instead of float Form inputs are annoying, let’s face it. There is a ton of data showing the more fields you have in a form, the higher the bounce rate of that form. I decided to play with radio buttons and try make them more like simple toggle buttons.


How to 'toggle' multiple elements with same class individually, If so, use something like this: $(document).on('click', '.reply-button' , function(){. Buttons Alert Buttons Outline Buttons Split Buttons Animated Buttons Fading Buttons Button on Image Social Media Buttons Read More Read Less Loading Buttons Download Buttons Pill Buttons Notification Button Icon Buttons Next/prev Buttons More Button in Nav Block Buttons Text Buttons Round Buttons Scroll To Top Button Forms


I am running into a problem applying a function to multiple elements with the same ID at once. Hi There, This happens because you are not allowed to use more than one of a unique ID per page.


Disabled Buttons Normal Button Disabled Button. Use the opacity property to add transparency to a button (creates a "disabled" look). Tip: You can also add the cursor property with a value of "not-allowed", which will display a "no parking sign" when you mouse over the button: