Reputation: 85
Is it possible to make a button in html visible if a variable in Javascript is true
ex code: var systemON = true;
And if systemON is true, I want a button to be visible in html.
Upvotes: 1
Views: 19703
Reputation: 2580
var systemON = false;
// checks if it is true
if (systemON) {
document.getElementById("button1").style.display = "block";
}
// checks if it is false
else {
document.getElementById("button1").style.display = "none";
}
var systemOFF = true;
// checks if it is true
if (systemOFF) {
document.getElementById("button2").style.display = "block";
}
// checks if it is false
else {
document.getElementById("button2").style.display = "none";
}
<button id="button1">Hidden</button>
<button id="button2">Displayed</button>
Upvotes: 0
Reputation: 85
I using this code to make a button visible and hidden, when needed
HTML:
<div class="system" id="SystemButton">
<p>System Runtime <span id="runtime"></span></p>
<p>System Failures: <span id="failures"></span></p>
<p><button id="Shutdown" onclick="systemDown(1)">Shutdown System</button></p>
</div>
JS:
var systemON = true;
if(systemON == true){
document.getElementById('systemButton').style.display = "block";
}else{
document.getElementById('systemButton').style.display = "none";
}
Upvotes: 0
Reputation: 802
Here you have a sample code that does what you ask:
var systemON = true;
if (systemON) {
document.getElementById("elementToShow").className = "showClass";
} else {
document.getElementById("elementToShow").className = "hideClass";
}
.showClass {
display: block;
}
.hideClass {
display: none;
}
<div id="elementToShow" class="hideClass">
Show me!
</div>
Upvotes: 0
Reputation: 178109
I prefer using a ternary boolean?when_true:when_false;
which is shorthand for
if (boolean) {
when_true;
}
else {
when_false;
}
Then assuming the statement is executed after the button is available in the DOM you can set the display like this:
document.getElementById("buttonID").style.display=systemON?"":"none"; // or "block":"none"
using CSS
#buttonID { display:none }
If you want the button to still take up space on the page, use
document.getElementById("buttonID").style.visibility=systemON?"visible":"hidden";
using CSS
#buttonID { visibility:hidden }
Upvotes: 3
Reputation: 185
well, yes..
if (sistemON) {
document.getElementById("yourButtonID").style.display = "block";
}
now am not sure if that is what you want or you to toggle visibility each time the variable changes in your code?
Upvotes: 1
Reputation: 1032
Try this : https://jsfiddle.net/820dzf3j/
var systemON = false;
var button = document.getElementById("myButton");
if(systemON) {
button.style.visibility = "hidden";
}
Upvotes: 0
Reputation: 315
if (systemON) {
document.getElementById("button").style.display = "none";
} else {
document.getElementById("button").style.display = "block";
}
should do it
Upvotes: 3