Step 1: Setup the HTML Document
The first step is to start by creating an HTML document, and inside that HTML file, simply include a div and a button with the following lines:
<div id="hideDiv">This is the div</div>
<button onclick="buttonClicked()">Click to Show</button>
</center>
In the above lines:
- A <div> is being created with a specific id that is “hideDiv”
- A button is created with the <button> tag, with an onclick property set equal to buttonClicked() function from the script file
At this point, the HTML document creates the following webpage on the browser:
A div with text and a button are being displayed onto the webpage.
Step 2: Setup the CSS File or the <style> tag
Create either a CSS file and link it with the HTML document or use a <style> tag. The div is not yet prominent enough. Therefore, adding some styling to it would be great:
background-color: yellowgreen;
height: 150px;
width: 150px;
}
In the above lines:
- The div is reference by using its ID as “hideDiv”
- A height and a width is specified for the div
- A background color has been given to the div
At this point, the HTML document looks like this:
However, to hide the div at the start, add one more line to the CSS file which is:
The whole CSS part would become:
display: none;
background-color: yellowgreen;
height: 150px;
width: 150px;
}
Now, the HTML looks like this:
The div is not being displayed on the HTML webpage at the start.
Step 3: Setup the JavaScript File or the <script> Tag
Now, to add functionality to the button press, simply add the following JavaScript lines to the HTML document by either using a <script> tag or a linked JavaScript file:
$("#hideDiv").show();
}
In these lines:
- A function buttonClicked() is created which would be called upon the click of the button due the the onclick() property defined inside the <button> tag
- The div is referenced by its ID that is “hideDiv”
- The show() method is called on the div which enables its display property
At this point, the HTML webpage works like following:
The div is displayed on button press and the problem has been fully tackled.
Wrap up
A div can easily be hidden at the start of a webpage with the help of the display property of the HTML element, and it can easily be displayed again upon button press with JavaScript. This article has displayed the step-by-step procedure to achieve the task at hand. However, as mentioned at the start of this article, there are multiple approaches to this problem, and none of them can be regarded as the best solution.