Ola
Ola

Reputation: 431

Javascript: How to show only one div on page load

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?

Upvotes: 2

Views: 7443

Answers (4)

Naga Sai A
Naga Sai A

Reputation: 10975

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';
}

Upvotes: 2

DanielC
DanielC

Reputation: 951

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');
}

Upvotes: 1

user2633356
user2633356

Reputation: 11

.Two{display:none;}

And then with javascript onclick event:

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

Upvotes: 1

Chris Zimmerman
Chris Zimmerman

Reputation: 331

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.

Upvotes: 1

Related Questions