The style
object on an element doesn't reflect its current styling, it reflects the styles set directly on it. So e.style.display == "none"
is false initially.
If you want to go that route, use getComputedStyle
, which returns an object with the "computed"¹ style for the element, taking CSS into account:
function insta() {
var a = document.getElementById("instaBalas");
if (getComputedStyle(a).display == "none") {
// ---^^^^^^^^^^^^^^^^^^^
a.style.display = "block";
} else {
a.style.display = "none";
}
}
function insta() {
var a = document.getElementById("instaBalas");
if (getComputedStyle(a).display == "none") {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
<button id="categoryBtn" onclick="insta()">instagram users</button>
<div id="instaBalas">instaBalas</div>
BUT, it would be better to define a class to hide the element, and then use toggle
on the element's classList
:
function insta() {
document.getElementById("instaBalas").classList.toggle("hidden");
}
Live Example:
function insta() {
document.getElementById("instaBalas").classList.toggle("hidden");
}
.hidden {
display: none;
}
<button id="categoryBtn" onclick="insta()">instagram users</button>
<div id="instaBalas">instaBalas</div>
All major browsers have classList
, and it can be polyfilled for obsolete browsers.
¹ It's not really the computed property value, it's the resolved or used property value, details here.