Accordion (expand/collapse)
Part of the JavaScript in Action section of Coddy's HTML journey — lesson 2 of 27.
An accordion is a UI component that lets you expand and collapse sections of content. It’s often used for FAQs (click a question → show the answer, click again → hide it).
The idea is simple: when you click a header, JavaScript toggles the visibility of the content below it.
Key points:
- We have a button and a content element that is hidden by default (
display: none).
- Clicking the button triggers the function and passes the ID of the element that should open.
- Inside the function:
- If the element is already showing (
display: block), we hide it (display: none). - Otherwise, we show it (
display: block).
- If the element is already showing (
<button onclick="toggle('p1')">Question 1</button>
<div id="p1" style="display:none;">Answer 1</div>
<script>
function toggle(id) {
const element = document.getElementById(id);
if (element.style.display === "block") {
element.style.display = "none";
} else {
element.style.display = "block";
}
}
</script>Challenge
EasyRight now, our accordion has three questions. Your task is to add a fourth one.
Steps:
- Create a new
<button>with the text: Should I add milk or drink it black? - Link it to a new panel by calling the function
onclick="togglePanel('q4')" - Create a
<div>with theid="q4"and classpanel. - Inside the div, write the answer:
It depends on your taste! Black coffee has stronger flavor, while milk softens the bitterness.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>FAQ Accordion</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>FAQ Coffee Lovers</h1>
<button class="accordion" onclick="togglePanel('q1')">What is the best way to brew coffee at home?</button>
<div id="q1" class="panel">
The French press and pour-over methods are popular for making rich, flavorful coffee at home.
</div>
<button class="accordion" onclick="togglePanel('q2')">Where do coffee beans come from?</button>
<div id="q2" class="panel">
Most coffee beans are grown in countries around the equator, such as Brazil, Ethiopia, and Colombia.
</div>
<button class="accordion" onclick="togglePanel('q3')">How late can I drink coffee?</button>
<div id="q3" class="panel">
It's best to avoid coffee 6 hours before bedtime, since caffeine can affect your sleep.
</div>
<script src="script.js"></script>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.