A <div> element is often used as a container and it will have many other elements, like a form. You might want to show or hide the <div> element when certain conditions are fulfilled.
One common scenario in JavaScript is toggling a <div> element's visibility with a button click.
<html> <body> <p> <input type="button" value="Show DIV" id="bt" onclick="toggle(this)"> </p> <!--The DIV element to toggle visibility. Its "display" property is set as "none". --> <div style="border:solid 1px #ddd; padding:10px; display:none;" id="cont"> <div> <label>Name:</label> <div><input id="name" name="yourname" /></div> </div> <div> <label>Age:</label> <div><input name="age" id="yourage" /></div></div> <div> <label>Additional Information (optional):</label> <div><textarea style="width:100%;" rows="5" cols="46"></textarea></div> </div> </div> </body> <script> function toggle(ele) { var cont = document.getElementById('cont'); if (cont.style.display == 'block') { cont.style.display = 'none'; document.getElementById(ele.id).value = 'Show DIV'; } else { cont.style.display = 'block'; document.getElementById(ele.id).value = 'Hide DIV'; } } </script> </html>
Using a straightforward if-else statement in your JavaScript code, you can easily toggle the display property of an HTML element. In the example above, the visibility of the <div> changes dynamically when the button is clicked.
You can further simplify the above code using a ternary operator. For example,
<script> function toggle(ele) { var cont = document.getElementById('cont'); cont.style.display = cont.style.display == 'none' ? 'block' : 'none'; } </html>
➡️ I have shared a similar example in Angular too.
Not just on button click, you can change the visibility of an element based on other conditions, like toggling the <div> element when someone select or un-select a value in SELECT dropdown list, etc.
Utilizing classList.toggle() with CSS classes
Now let's improve the above toggle functions. By using CSS classes and classList.toggle(), you get a simpler, more flexible way to show or hide elements. No messy inline styles required.
<style> .hidden { display: none; } </style> <script> function toggle(button) { const cont = document.getElementById('cont'); cont.classList.toggle('hidden'); button.value = cont.classList.contains('hidden') ? 'Show DIV' : 'Hide DIV'; } </html>
The above code uses CSS class to manage the styling and JavaScript to handle the logic. This approach enhances scalability by making it easier to manage multiple visibility states or transitions, and improves performance by reducing reliance on inline style manipulation.