Blog

How to Toggle a Div with JavaScript, jQuery, and CSS

Showing and hiding content is one of the most common interface patterns in modern web development. A developer may use it for menus, accordions, FAQ sections, notification panels, product filters, or dashboard widgets. The basic idea is simple: a div is either visible or hidden, and a user action, such as clicking a button, changes that state.

TLDR: A div can be toggled with plain JavaScript, jQuery, or CSS, depending on how much control the project needs. For example, a support page with 12 FAQ answers can hide all answers by default and reveal each one when its question is clicked, reducing visible page length by around 70%. JavaScript offers flexibility, jQuery provides shorter syntax, and CSS works well for simple no-script interactions. In most modern projects, plain JavaScript is often the cleanest choice.

What Does It Mean to Toggle a Div?

To toggle a div means to switch it between two states, usually visible and hidden. This can be achieved by changing inline styles, adding or removing a CSS class, using jQuery helper methods, or relying on CSS selectors such as :checked.

A typical example includes a button and a content block:

<button id="toggleBtn">Show or Hide Content</button>

<div id="contentBox">
  This content can be toggled.
</div>

The goal is to make the contentBox appear or disappear when the button is clicked.

Method 1: Toggling a Div with Plain JavaScript

Plain JavaScript is widely recommended because it does not require any external library. It is fast, browser-supported, and easy to maintain in small or medium projects.

One direct method is to check the current display value and change it:

<button id="toggleBtn">Toggle Div</button>

<div id="contentBox" style="display: none;">
  This div is toggled with JavaScript.
</div>

<script>
  const button = document.getElementById("toggleBtn");
  const box = document.getElementById("contentBox");

  button.addEventListener("click", function() {
    if (box.style.display === "none") {
      box.style.display = "block";
    } else {
      box.style.display = "none";
    }
  });
</script>

This approach is easy to understand, but it has one limitation: it mixes behavior with direct style changes. In larger projects, a class-based method is usually better.

Using classList.toggle()

A cleaner JavaScript solution uses classList.toggle(). The CSS controls how the div looks, while JavaScript only changes the class.

<button id="toggleBtn">Toggle Div</button>

<div id="contentBox" class="hidden">
  This div is toggled by adding and removing a class.
</div>

<style>
  .hidden {
    display: none;
  }
</style>

<script>
  const button = document.getElementById("toggleBtn");
  const box = document.getElementById("contentBox");

  button.addEventListener("click", function() {
    box.classList.toggle("hidden");
  });
</script>

This version is more maintainable because the visual rule stays in CSS. A developer can later change display: none; to another effect without rewriting the JavaScript.

Method 2: Toggling a Div with jQuery

jQuery was once the standard way to simplify DOM manipulation. Although many modern projects now use plain JavaScript or frameworks, jQuery is still found in many existing websites, WordPress themes, admin panels, and legacy applications.

With jQuery, toggling a div is very short:

<button id="toggleBtn">Toggle Div</button>

<div id="contentBox">
  This div is toggled with jQuery.
</div>

<script>
  $("#toggleBtn").on("click", function() {
    $("#contentBox").toggle();
  });
</script>

The .toggle() method automatically shows the div if it is hidden and hides it if it is visible. This makes the code compact and readable.

jQuery also supports animation effects:

$("#toggleBtn").on("click", function() {
  $("#contentBox").slideToggle(300);
});

In this example, slideToggle(300) animates the div over 300 milliseconds. This is useful for accordions, navigation menus, and content panels where a smooth transition improves the user experience.

Method 3: Toggling a Div with CSS Only

CSS can also toggle a div without JavaScript. This is useful when the interaction is simple and does not require complex logic. A common technique uses a hidden checkbox and the :checked selector.

<label for="toggleBox" class="toggleLabel">Toggle Content</label>
<input type="checkbox" id="toggleBox">

<div class="contentBox">
  This div is toggled with CSS only.
</div>

<style>
  #toggleBox {
    display: none;
  }

  .contentBox {
    display: none;
  }

  #toggleBox:checked + .contentBox {
    display: block;
  }

  .toggleLabel {
    cursor: pointer;
    font-weight: bold;
  }
</style>

However, this exact structure depends on the placement of elements. Since the selector + targets the next sibling, the div must come immediately after the checkbox. If the markup is more complex, CSS-only toggling may become difficult to manage.

Adding Smooth Transitions

Using display: none; is simple, but it cannot be smoothly animated. For transitions, a developer often toggles properties such as max-height, opacity, or visibility.

.contentBox {
  max-height: 0;
  opacity: 0;
  overflow: hidden;
  transition: max-height 0.3s ease, opacity 0.3s ease;
}

.contentBox.open {
  max-height: 300px;
  opacity: 1;
}

Then JavaScript can toggle the open class:

button.addEventListener("click", function() {
  box.classList.toggle("open");
});

This method creates a smoother experience than instantly hiding and showing the element. It is especially useful for mobile menus and collapsible information sections.

Accessibility Considerations

A toggled div should also be understandable to assistive technologies. A button that expands content should include attributes such as aria-expanded and aria-controls.

<button id="toggleBtn" aria-expanded="false" aria-controls="contentBox">
  Toggle Content
</button>

<div id="contentBox" hidden>
  Accessible hidden content.
</div>

The JavaScript can then update the state:

button.addEventListener("click", function() {
  const isHidden = box.hasAttribute("hidden");

  if (isHidden) {
    box.removeAttribute("hidden");
    button.setAttribute("aria-expanded", "true");
  } else {
    box.setAttribute("hidden", "");
    button.setAttribute("aria-expanded", "false");
  }
});

This approach helps screen reader users understand whether the content is currently expanded or collapsed. Accessibility is not only a technical improvement; it can also affect usability, compliance, and overall audience reach.

Which Method Should Be Used?

The best method depends on the project:

  • Plain JavaScript: Best for most modern websites, especially when no library is needed.
  • jQuery: Useful for older websites or projects where jQuery is already loaded.
  • CSS only: Good for simple toggles that do not require dynamic logic.
  • Class-based toggling: Best for maintainable code and clean separation between style and behavior.

For a new website, a developer will usually choose JavaScript with classList.toggle(). It keeps the code lightweight and gives enough control for styling, animation, and accessibility.

Common Mistakes to Avoid

  • Using inline styles everywhere: This can make future design changes harder.
  • Forgetting accessibility: Toggle buttons should communicate expanded and collapsed states.
  • Animating display: The display property cannot transition smoothly.
  • Loading jQuery unnecessarily: If only one toggle is needed, plain JavaScript is usually enough.
  • Ignoring default state: The div should have a clear initial visible or hidden state.

FAQ

Can a div be toggled without JavaScript?

Yes. A div can be toggled with CSS only by using a checkbox, label, and the :checked selector. This works best for simple interactions.

Is jQuery still good for toggling divs?

Yes, especially on websites where jQuery is already included. However, for new lightweight projects, plain JavaScript is often preferred.

What is the simplest JavaScript way to toggle a div?

The simplest modern method is element.classList.toggle("hidden"), paired with a CSS class such as .hidden { display: none; }.

Can a hidden div be animated?

Yes, but not directly with display: none;. Smooth animations usually use opacity, max-height, transform, or similar properties.

Should hidden content use display none or the hidden attribute?

Both can work. The hidden attribute is semantic and useful for accessibility, while CSS classes provide more styling flexibility.

To top