Menu
CoddyTech

아코디언(펼치기/접기)

Coddy HTML 여정의 JavaScript 실전 섹션에 포함된 레슨. 27개 중 2번째.

아코디언은 콘텐츠 섹션을 펼치고 접을 수 있게 해 주는 UI 구성 요소입니다. FAQ에서 자주 사용됩니다(질문을 클릭하면 답변 표시 → 다시 클릭하면 숨김).
간단한 원리입니다. 헤더를 클릭하면 JavaScript가 아래 콘텐츠의 표시 여부를 전환합니다.

핵심 사항:

  1. 버튼과 기본적으로 숨겨져 있는 콘텐츠 요소(display: none)가 있습니다.
  1. 버튼을 클릭하면 함수가 호출되고 열어야 하는 요소의 ID가 전달됩니다.
  1. 함수 내부에서:
    • 요소가 이미 표시되고 있으면(display: block), 숨깁니다(display: none).
    • 그렇지 않으면 표시합니다(display: block).
<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 icon

챌린지

쉬움

현재 아코디언에는 질문이 세 개 있습니다. 네 번째 질문을 추가하는 것이 과제입니다.

단계:

  1. 다음 텍스트가 있는 새 <button>을 만드세요: Should I add milk or drink it black?
  2. 함수 onclick="togglePanel('q4')"을 호출하여 새 패널에 연결하세요.
  3. id="q4"와 클래스 panel을 가진 <div>를 만드세요.
  4. div 안에 답을 작성하세요:
    It depends on your taste! Black coffee has stronger flavor, while milk softens the bitterness.

직접 해보기

<!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>
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

JavaScript 실전의 모든 레슨

직접 연습해 보세요: Web 플레이그라운드