Home > Software engineering >  Hide / Show toggle button doesn't start with content hidden
Hide / Show toggle button doesn't start with content hidden

Time:01-05

It works but it doesn't start off with my 'more details' content toggled to hidden. It starts off with the content showing. I have rewritten this 10 times and can't figure it out.

function toggle() {
  let Text = document.getElementById('moreDetails');

  if (Text.style.display == "none") {
    Text.style.display = "block";
  } else {
    Text.style.display = "none";
  }
}
<div id="moreDetails">

  <h3> 001 </h3>

  <h3> Saturate Radio </h3>

  <h4> N00DS </h4>

</div>

<button title="Click to Show" type="button" onclick="toggle()">MoreDetails</button>

CodePudding user response:

add style display none to your div id moreDetails

<div id="moreDetails" style="display: none">

or you can use like this also

<script>
function toggle(){
    let Text = document.getElementById('moreDetails');

    if(Text.style.display == "none"){
        Text.style.display= "block";
    }
    else {
        Text.style.display = "none";
    }
}
document.getElementById("moreDetails").style.display = "none";
 
</script>

or you can use ternary operator

<script>
    function toggle(){
        const Text = document.getElementById('moreDetails');
        Text.style.display = Text.style.display == "none" ? "block" : "none";
    }
    document.getElementById("moreDetails").style.display = "none";
</script>

CodePudding user response:

To start with more details hidden, you should add style="display: none;" to your div; Here's the code:

function toggle() {
  let Text = document.getElementById('moreDetails');

  if (Text.style.display == "none") {
Text.style.display = "block";
  } else {
Text.style.display = "none";
  }
}
<div id="moreDetails" style="display: none;">

  <h3> 001 </h3>

  <h3> Saturate Radio </h3>

  <h4> N00DS </h4>

</div>

<button title="Click to Show"  type="button" onclick="toggle()">MoreDetails</button>

CodePudding user response:

Add display none for div.

function toggle(){
    const Text = document.getElementById('moreDetails');
    Text.style.display = Text.style.display == "none" ? "block" : "none";
}
<div id="moreDetails" style="display: none">

  <h3> 001 </h3>

  <h3> Saturate Radio </h3>

  <h4> N00DS </h4>

</div>

<button title="Click to Show" type="button" onclick="toggle()">MoreDetails</button>

  •  Tags:  
  • Related