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>
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>