Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initially I want ON button to be display block and off to display none, if I click ON button, OFF appears & On disappears, and vice versa

I am trying to achieve a toggle effect using display properties, only one button should be on display at a time, while the other is hidden and vice versa. Currently, I am able to hide the off button if I click any of the buttons, so what do I do to get only one displayed at a time

function myFunction() {
  var x = document.getElementById("on");
  var y = document.getElementById("off");
  
  y.style.display ="none";

  if (x.style.display === "none") 
  {
    x.style.display = "block";
  } 
  else 
  {
    y.style.display = "none";
    x.style.display = "block";
  }
}
<button onclick="myFunction()" id="on">ON</button>
<button onclick="myFunction()" id="off">OFF</button>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue with your logic is that you need to switch the display state of both elements within the function you call:

var on = document.getElementById("on");
var off = document.getElementById("off");
  
function myFunction() {  
  if (on.style.display === "none") {  
    off.style.display = "none";
    on.style.display = "block";
  } else {
    off.style.display = "block";
    on.style.display = "none";
  }
}
<button onclick="myFunction()" id="on">ON</button>
<button onclick="myFunction()" id="off" style="display: none;">OFF</button>

Another way to do what you require would be to use a CSS class to hide the required element. This avoids the need for the if condition. You can then use classList.toggle() to switch the class on/off on each element on successive clicks. Something like this:

let toggles = document.querySelectorAll('.toggle');

toggles.forEach(toggle => {
  toggle.addEventListener('click', e => {
    toggles.forEach(el => el.classList.toggle('hide'));
  });
});
.hide { display: none; }
<button class="toggle" id="on">ON</button>
<button class="toggle hide" id="off">OFF</button>

Or even more simply using jQuery:

let $toggles = $('.toggle').on('click', () => $toggles.toggleClass('hide'));
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button class="toggle" id="on">ON</button>
<button class="toggle hide" id="off">OFF</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading