I have a button that should toggle between visibility visible
and hidden
, and even though I specify in CSS that the div
has visibility: hidden
, the JS code first sees the CSS as blank (as if I did not specify the style).
Only after the second click (mouseup
event in my case), it detects the visibility and the toggling starts working, why?
Here’s a snippet:
let button = document.querySelector("#button");
button.addEventListener("mouseup", toggleVisibility)
function toggleVisibility() {
let div = document.getElementById("div");
if (div.style.visibility === "hidden") {
div.style.visibility = "visible";
} else {
div.style.visibility = "hidden";
}
}
#div {
visibility: hidden;
}
<button id="button"> toggle </button>
<div id="div">
<h1> Hello, World! </h1>
</div>
3
Answers
div.style
reads from thestyle
attribute not the actual applied styles. To fix this you can either use inline styling or get the computed style via getComputedStyle().Example inline styling:
Example
getComputedStyle()
:EDIT: As pointed out in the comments toggling a class is another alternative. This is especially useful if you need to change more then one style.
To evaluate style properties of an element, you need to use the
window.getComputedStyle()
method.In your case, the code should be:
Soi if you don’t want to use inline-css;