Blog Logo

27-Feb-2024 ~ 2 min read

How to Hide a Div with Vanilla JavaScript


Implementing a Toggle Show/Hide Button with Inline Vanilla JavaScript

Creating a toggle show/hide button with inline vanilla JavaScript is a straightforward task that can be accomplished with just a few lines of code. In this guide, we’ll demonstrate how to implement a toggle button that shows or hides a target element on each click.

Steps:

1. Add a button element to your HTML:

Include a button element in your HTML with an onclick attribute to trigger the JavaScript function.

2. Define an inline JavaScript function:

Use the onclick attribute of the button to define an inline JavaScript function that toggles the visibility of the target element using its style.display property.

3. Example code:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Toggle Show/Hide Button</title>
  </head>
  <body>
    <div id="targetDiv" style="border: 1px solid black; padding: 10px;">
      This is the target div.
    </div>

    <button onclick="toggleVisibility()">Toggle Show/Hide</button>

    <script>
      function toggleVisibility() {
        const targetDiv = document.getElementById('targetDiv');
        if (targetDiv.style.display === 'none') {
          targetDiv.style.display = 'block';
        } else {
          targetDiv.style.display = 'none';
        }
      }
    </script>
  </body>
</html>

Conclusion:

Implementing a toggle show/hide button with inline vanilla JavaScript is simple and requires minimal code. By defining a JavaScript function directly within the onclick attribute of the button element, you achieve a convenient and efficient solution for toggling the visibility of the target element dynamically.