https://gistpreview.github.io/?020a173406f4b41b77e832d7fc33237d
Last active
November 24, 2021 01:05
-
-
Save cagataycali/020a173406f4b41b77e832d7fc33237d to your computer and use it in GitHub Desktop.
[HTML] Accordion menu - simple
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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