Skip to content

Instantly share code, notes, and snippets.

@cagataycali
Last active November 24, 2021 01:05
Show Gist options
  • Save cagataycali/020a173406f4b41b77e832d7fc33237d to your computer and use it in GitHub Desktop.
Save cagataycali/020a173406f4b41b77e832d7fc33237d to your computer and use it in GitHub Desktop.
[HTML] Accordion menu - simple
<html>
<head>
<title>Accordion menu - Simple</title>
<style>
.accordion-wrapper {
display: flex;
align-items: center;
flex-direction: column;
}
.accordion {
padding: 1rem;
margin: 1rem;
}
.accordion-button {
margin-top: 1rem;
display: block;
width: 185px;
height: 45px;
background: black;
color: white;
border-color: transparent;
border-radius: 6px;
}
.accordion-panel {
display: none;
}
.accordion-panel.active {
display: block;
}
</style>
</head>
<body>
<div id="app">
<div class="accordion">
<button
class="accordion-button"
aria-controls="panel-1"
data-id="1"
aria-expanded="false"
>
Panel 1
</button>
<div class="accordion-panel active" id="panel-1" aria-hidden="true">
<span>Panel 1</span>
</div>
<button
class="accordion-button"
aria-controls="panel-2"
data-id="2"
aria-expanded="false"
>
Panel 2
</button>
<div class="accordion-panel" id="panel-2" aria-hidden="true">
<span>Panel 2</span>
</div>
<button
class="accordion-button"
aria-controls="panel-3"
data-id="3"
aria-expanded="false"
>
Panel 3
</button>
<div class="accordion-panel" id="panel-3" aria-hidden="true">
<span>Panel 3</span>
</div>
</div>
</div>
<script>
const app = document.getElementById("app");
app.addEventListener("click", handleClick);
function handleClick(e) {
const isButton = e.target.classList.contains("accordion-button");
if (isButton) {
// Close other panels,
const accordion = e.target.parentElement;
const targetPanelId = e.target.dataset.id;
closeAllPanels(accordion, targetPanelId);
togglePanel(document.querySelector(`#panel-${targetPanelId}`));
}
}
function closeAllPanels(accordion, current) {
const activePanels = accordion.querySelectorAll(
".accordion-panel.active"
);
for (const panel of activePanels) {
if (!panel.id.includes(current)) togglePanel(panel);
}
}
function togglePanel(panel) {
let isHidden = panel.getAttribute("aria-hidden") === "true";
panel.setAttribute("aria-hidden", !isHidden);
panel.classList.toggle("active");
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment