I have this code:
function UnhideFunction() {
var x = document.getElementById("MyShow");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
.myhide {
display: none;
}
<button onclick="UnhideFunction()">SHOW ME</button>
<div id="MyShow" class="myhide">
SOME TEXT
The problem is SOME TEXT shows only when I click SHOW ME twice.
How do I fix it?
Thanks
>Solution :
The issue you’re encountering is likely due to how the display property is being set and checked. When you initially hide the element by setting display: none;, the x.style.display property will be an empty string, not "none".
This will fix the problem
<script>
function UnhideFunction() {
var x = document.getElementById("MyShow");
if (getComputedStyle(x).display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>