Show And Hide DIVs On Button Click With JavaScript

JavaScript is a versatile and widely-used programming language that can be used for a variety of web development tasks, including showing and hiding elements on a web page. In this article, we'll look at how to show and hide DIVs on a button click with JavaScript.

Getting Started

To get started, we'll first create a basic HTML structure with two DIVs and a button. The first DIV will contain some content, while the second DIV will be hidden by default.

<button id="toggleBtn">Show/Hide DIV</button>
<div id="firstDiv">This is the first DIV.</div>
<div id="secondDiv" style="display:none;">This is the second DIV.</div>

The "display:none" style for the second DIV ensures that it is hidden when the page loads. The button will be used to toggle the visibility of the second DIV.

Show and Hide DIVs on Button Click

Next, we'll add a JavaScript function that will be executed when the button is clicked. This function will toggle the visibility of the second DIV by changing its display style.

<script>
    document.getElementById("toggleBtn").onclick = function() {
        var secondDiv = document.getElementById("secondDiv");
        if (secondDiv.style.display === "none") {
            secondDiv.style.display = "block";
        } else {
            secondDiv.style.display = "none";
        }
    };
</script>

The JavaScript code first gets a reference to the button element using the "getElementById" method. Then, it adds a click event handler to the button that will execute the function. Inside the function, we get a reference to the second DIV element and use an if-else statement to toggle its display style between "block" and "none".

Conclusion

In this article, we've looked at how to show and hide DIVs on a button click with JavaScript. We've seen how to create a basic HTML structure with two DIVs and a button, and how to use JavaScript to toggle the visibility of the second DIV. With this simple technique, you can add dynamic and interactive elements to your web pages.


Similar Articles