DerpoRex DerpoRex - 28 days ago 10
Javascript Question

Button not working second time

Why doesn't this change the name of the button when clicked a second time?

<div id="randomInfo">
<p id="randomInfo-data">This is going to be a space taker.</p>
<button class="chipTabsIndex" onclick="randomInfoExpand()" id="randomInfo-expandClose">Show</button>
<script>
function randomInfoExpand() {
if (closeData === 1) {
document.getElementById("randomInfo-expandClose").innerHTML = "Show";
var closeData = 0;
} if (closeData !== 1) {
document.getElementById("randomInfo-expandClose").innerHTML = "Hide";
var closeData = 1;
}
}
</script>
</div>

Answer

Since you had declared closeData inside the if loop of function, its scope was destroyed after first execution and hence it wasn't updating name. try this solution:

<div id="randomInfo">
        <p id="randomInfo-data">This is going to be a space taker.</p>
        <button class="chipTabsIndex" onclick="randomInfoExpand()" id="randomInfo-expandClose">Show</button>
    </div>
    <script>
        let closeData = 1;
        function randomInfoExpand() {
            if (closeData === 1) {
                document.getElementById("randomInfo-expandClose").innerHTML = "Show";
                closeData = 0;
            }
            else if (closeData === 0) {
                document.getElementById("randomInfo-expandClose").innerHTML = "Hide";
                closeData = 1;
            }
        }
    </script>
Comments