I want a button that toggles display none and block. It works the first time hiding the H1, but doesn't work the second time. I looked inside the console, and it's only toggling the first if statement.
<html>
<head>
<style>
h1 {display: block;}
</style>
</head>
<body>
<h1 id="hello">hello there</h1>
<button onclick="hide()">hide</button>
</body>
<script>
var h1 = document.getElementById("hello")
function hide() {
if (h1.style.display ="block"){
h1.style.display ="none"
console.log ("display none")
} else if (h1.style.display ="none"){
h1.style.display ="block"
console.log ("display block")
}
}
</script>
</html>
I have tried
if (h1.style.display == "none")
but it doesn't work at all then. Doesn't even toggle the first time.
=is assignment.==and===are comparisonif (h1.style.display = "block")is alwaystruebecause it's an expression that returns non zero length string in this case"block". your firstifblock always istrueby doing thisif (h1.style.display = "block")h1toblockother wise none of if statements work: add this to yourh1tagstyle="display:block;"dont forget to replace = to == or ===