0

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.

6
  • 1
    = is assignment. == and === are comparison Commented Aug 2, 2020 at 18:01
  • Because of your code missing on if block if (h1.style.display ="block"){ you shoul use doubke equal == Commented Aug 2, 2020 at 18:02
  • I thought that as well, but having == or === doesn't toggle the display at all Commented Aug 2, 2020 at 18:03
  • it doesn't matter you tried == or === , in your code if (h1.style.display = "block") is always true because it's an expression that returns non zero length string in this case "block". your first if block always is true by doing this if (h1.style.display = "block") Commented Aug 2, 2020 at 18:10
  • ANSWER: the reason it doesn't work is because you must initial style.display of h1 to block other wise none of if statements work: add this to your h1 tag style="display:block;" dont forget to replace = to == or === Commented Aug 2, 2020 at 18:18

7 Answers 7

1

Notice that you assign instead of check:

if (h1.style.display ="block")

One = means to assign 'block' to the display property and the it will return true and therefore it always will set the display to false.

you should do this like this:

if (h1.style.display == "block")

And

} else if (h1.style.display == "none"){

You also can make your code more efficient by using some ES6 features:

h1.style.display = h1.style.display == 'block' ? 'none' : 'block'

The ? mark is a short if and the : is the short else.

So it basically says if the value is block, set it to none, else, set it to block.

Read more about Operators in JS and ES6.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried this at first, but then it wouldn't toggle the display at all
0

toggle can be directly assumed on class assignation

see doc : https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

sample code:

const myHello      = document.getElementById('hello')
  ,   mybtShowHide = document.getElementById('bt-show-hide')


mybtShowHide.onclick =() =>
  {
  let status = myHello.classList.toggle('noDisplay')

  console.clear()  
  if (status) console.log ("display none")
  else       console.log ("display block")
  }
.noDisplay { display: none; }
<h1 id="hello">hello there</h1>
<button id="bt-show-hide"> show / hide</button>

Comments

0

h1.style refers to the style attribute on the HTML tag. For more control, I would recommend using classList to determine if a hide class is on the element. I tested the following code and it works.

<html>
    <head>
        <style>
            .hide {display: none;}
        </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.classList.contains('hide')) {
                h1.classList.remove('hide');
            } else {
                h1.classList.add('hide');
            }
        }
    </script>
</html>

Comments

0

The simplest answer that I found was this:

it doesn't matter you tried == or === , in your code if (h1.style.display = "block") is always true because it's an expression that returns non zero length string in this case "block". your first if block always is true by doing this if (h1.style.display = "block")

ANSWER: the reason it doesn't work is because you must initial style.display of h1 to block other wise none of if statements work: add this to your h1 tag style="display:block;" dont forget to replace = to == or === –

And so I made the code like this:

<html>
    <head>
        <style>
            h1 {}
        </style>
    </head>
    <body>
        <h1 id="hello">hello there</h1>
        <button onclick="hide()">hide</button>
    </body>
    <script>
        var h1 = document.getElementById("hello")

        h1.style.display = "block"

        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>

Not the cleanest, but it works

2 Comments

The assignment "expression" returns the value that has been assigned to the left side. E.g. if(myVar = 0) { console.log('it will not work'); } will not execute the if
Even if you want to assign and check for the value at the same time, do not do this because it makes the code less readable. Instead do the assignment and the check the variable in the if
0

You are using assignment = in the if and else if conditions. You should use == or === to check for equality. Also you don't account for the initial case where element.style.display be empty e.g. ""

But the real answer is: don't do this. Use a MVC, MVVM, MV* framework such as React, Angular, etc to hide/show things for you based on some model. These can handle much more complicated model and transform the UI in many other ways for you.

2 Comments

lol I'm just starting out with javascript and messing around for now. I'll get to react eventually
Alright, it is very good you have that on your mind. I think it is even better you make sure you know how the plain HTML/JavaScript work also before (or while) using those frameworks. Enjoy learning JS!
0

<html>
    <head>
        
    </head>
    <body>
        <h1 id="hello">hello there</h1>
        <button onclick="hide()">hide</button>
    </body>
    <script>
        var h1 = document.getElementById("hello")

        function hide() {
            if (hello.hidden==true){
                hello.hidden=false;
        
            } 
            else{
                hello.hidden=true;
            }
        }
    </script>
</html>

Comments

0

There is two things missing in above code .

  1. To use equality operator than assignment operator for comparison: h1.style.display === "block"

  2. a) To get actual element styling need to use DOM CSS . b) To access style property from DOM need to use inline styling .

Method a: using DOM CSS:

var h1 = document.getElementById("hello");
       
        function hide() {
        
        var h1Display = window.getComputedStyle(h1).display;
            if (h1Display === "block"){
                h1.style.display ="none";
            } else if (h1Display === "none"){
                h1.style.display ="block"
            }
        }
h1 {display: block;}
<html>
        <body>
            <h1 id="hello" >hello there</h1>
            <button onclick="hide()">hide</button>
        </body>
  </html>
Method b) using inline styling :

<html>
<h1 id="hello" style="display:block" >hello there</h1>
     <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>

  

 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.