Bootstrap is a fantastic framework for building responsive and user-friendly websites, and one common task developers often encounter is hiding a HTML element by default and then showing it when an action is taken. In this article, we will walk through how to achieve this using Bootstrap.
To start, let's set up a basic HTML file and include the Bootstrap CDN to access its library. Then, create a simple div element that we want to hide initially and show on click. In your HTML file, add the following code snippet:
<title>Hide Div By Default And Show It On Click With Bootstrap</title>
<div class="container">
<div id="myDiv" class="bg-primary text-center text-white p-3">
This is the hidden div content.
</div>
<button id="showDivBtn" class="btn btn-primary mt-3">Show Div</button>
</div>
In the code above, we have a div with the ID `myDiv` which is set to initially be hidden using the `display: none;` style attribute. We've also added a Bootstrap button with the ID `showDivBtn` that we will use to trigger the display of the hidden div.
Next, let's write some JavaScript code to handle the click event and show the hidden div when the button is clicked. Add the following script section at the end of your HTML body:
document.getElementById("showDivBtn").addEventListener("click", function() {
var myDiv = document.getElementById("myDiv");
if (myDiv.style.display === "none") {
myDiv.style.display = "block";
} else {
myDiv.style.display = "none";
}
});
In the script above, we've added an event listener to the button with the ID `showDivBtn`. When the button is clicked, the script checks the current display style of the `myDiv` element. If it's set to `none`, the script switches it to `block`, making the div visible. If the div is already visible, clicking the button will hide it again by setting the display back to `none`.
Now, open your HTML file in a browser, and you should see the hidden div and the "Show Div" button. Clicking the button will toggle the visibility of the div. This simple functionality can be useful in various scenarios on your website.
And there you have it! You've successfully hidden a div by default and made it visible on click using Bootstrap. Keep experimenting with Bootstrap's utilities and JavaScript to create interactive and user-friendly web interfaces.