<div class="lab-container">
<h1 class="lab-title">Pure JavaScript-based display toggle</h1>
<div class="lab-description">
<p>Demonstrating a no-nonsense display toggle done the right way with simple vanilla JavaScript. <a href="/blog/javascript-display-toggle/">Grab the code and explanation</a>.</p>
</div>
<div class="lab-inner">
<button id="trigger">
Click to show/hide the target
</button>
<div id="product-filters">The target element</div>
</div>
</div>
<button
type="button"
aria-controls="product-filters"
onclick="toggleDisplay(document.getElementById('product-filters'), this, 'flex')">
Toggle Filters
</button>
:root {
--accent: #2980b9;
}
.lab-container {
min-height: 100dvh;
padding: 8rem 2rem;
}
.lab-inner {
max-width: 40rem;
width: 100%;
}
#product-filters {
display: block;
opacity: 1;
position: absolute;
transition:
display 200ms allow-discrete,
opacity 200ms ease-in-out;
@starting-style {
display: none;
opacity: 0;
}
}
/* Closed state */
#product-filters[style*="display: none"] {
opacity: 0;
}
const toggleDisplay = (
target,
trigger,
display = "block"
) => {
const appliedDisplay =
window.getComputedStyle(target).display;
const isHidden = appliedDisplay === "none";
target.style.display = isHidden
? display
: "none";
trigger.setAttribute(
"aria-expanded",
String(isHidden)
);
};
toggleDisplay(document.getElementById('product-filters'), document.getElementById('trigger'));