2

I have two div in a html file.

<div class="one" id="firstDiv">
</div>

<div class="Two" id="SecondDiv">
</div>

I want to show only div class = "one" when the page loads and eventually show div two when a click action occurs. I know how to fade in onclick event but how can I only show the first div when the page loads?

Ola
  • 431
  • 1
  • 8
  • 28
  • 2
    you can make class= "Two" display:none and make it available onclick as mentioned – Naga Sai A Apr 30 '17 at 22:24
  • You can omit the second div and create it programmatically on button click. Or you can add a class that hides it initially and remove it on button click – Brian Apr 30 '17 at 22:24
  • Possible duplicate of [Show/hide 'div' using JavaScript](http://stackoverflow.com/questions/21070101/show-hide-div-using-javascript) – BigSpicyPotato Apr 30 '17 at 22:25

4 Answers4

2

To achieve expected result , use below option
Option 1:
1.Create function to hide the div using id
2.Use function on body as onload function
Codepen url for reference- https://codepen.io/nagasai/pen/JNNrpM

Option 2:
1. Make #SecondDiv display:none initially
2. And make it available onclick using display:block
Codepen url for reference- https://codepen.io/nagasai/pen/KmmXez

JS:

var divTwo = document.getElementById('SecondDiv');
function hideDiv(){
  divTwo.style.display ='none';
}

function showDiv(){
  divTwo.style.display ='block';
}

HTML:

<html>
  <body onload="hideDiv()">
    <div class="one" id="firstDiv">111
</div>

<div class="Two" id="SecondDiv">222
</div>

    <button onclick="showDiv()">show Div Two</button>
  </body>
</html>

Option2:

HTML:

<html>
  <body>
    <div class="one" id="firstDiv">111
</div>

<div class="Two" id="SecondDiv">222
</div>

    <button onclick="showDiv()">show Div Two</button>
  </body>
</html>

CSS:

.Two{
  display:none
}

JS:

function showDiv(){
  var divTwo = document.getElementById('SecondDiv');
  divTwo.style.display ='block';
}
Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
1

You can add a click event so that when the body is clicked, you add the other div to the page with createElement():

https://www.w3schools.com/jsref/met_document_createelement.asp

If you only want the div to be added once, you can remove the event listener along with the creation of the div.

Chris Zimmerman
  • 331
  • 2
  • 10
1

If you want the div to be hidden at the start you could use CSS to apply the hidden value such as:

<div class="hidden" id="someIdVal">Lorem Ipsum</div>

.hidden{
  display: none;
}

Then with JS remove/add the class with:

function toggleHidden(id){
  document.getElementById(id).classList.toggle('hidden');
}
DanielC
  • 921
  • 7
  • 12
1

.Two{display:none;}

And then with javascript onclick event:

document.getElementById("SecondDiv").style.display = "block";