Menu
Coddy logo textTech

닫기 가능한 배너

Coddy HTML 여정의 JavaScript in Action 섹션에 포함된 레슨 — 27개 중 9번째.

닫을 수 있는 배너(dismissible banner)는 페이지의 상단(또는 하단)에 나타나며 사용자가 직접 닫을 수 있는 알림 또는 메시지 바입니다. 이는 주로 쿠키 정책, 공지 사항 또는 경고와 같은 중요한 정보를 표시하는 데 사용됩니다. 핵심 기능은 사용자가 페이지를 새로고침하지 않고도 배너를 숨길 수 있게 해주는 닫기(×) 버튼입니다.

먼저, HTML 구조를 추가해 보겠습니다:

<div class="banner" id="banner">
  <p>This is an important announcement!</p>
  <button id="closeBanner">X</button>
</div>

다음으로, 배너의 스타일을 지정하기 위해 몇 가지 기본적인 CSS를 추가해 보겠습니다:

.banner {
  background-color: #1e90ff;
  color: white;
  padding: 15px 20px;
  text-align: center;
  position: relative;

}

.banner button {
  position: absolute;
  right: 10px;
  top: 10px;
  border: none;

  cursor: pointer;
}

마지막으로, 배너를 닫을 수 있도록 JavaScript를 추가합니다:

const banner = document.getElementById('banner');
const closeBtn = document.getElementById('closeBanner');

closeBtn.addEventListener('click', function() {
  banner.style.display = 'none';
});

닫기 버튼을 클릭하면 배너가 사라집니다.

challenge icon

챌린지

쉬움

사용자가 닫기 버튼을 클릭하면 배너가 사라지게 하려고 합니다.

  1. 닫기 버튼을 클릭했을 때 함수가 실행되도록 이벤트 리스너를 추가하세요.
  2. 이 함수 내부에서 배너 요소의 display 속성을 none으로 설정하여 숨겨지도록 하세요.

직접 해보기

<!DOCTYPE html>
<html>
<head>
  <title>Dismissible Banner Example</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <!-- Banner -->
  <div class="banner" id="banner">
    <p>Big News! Our new course is live. Enroll today and get 30% off!</p>
    <button id="closeBanner">&times;</button>
  </div>

  <!-- Page Content -->
  <header class="hero">
    <h1>Welcome to CodeLearn</h1>
    <p>Practical lessons to sharpen your web development skills 🚀</p>
  </header>

  <main class="content">
    <section>
      <h2>Learn by Doing</h2>
      <p>Each lesson comes with tasks and challenges so you can practice immediately.</p>
    </section>

    <section>
      <h2>Topics We Cover</h2>
      <ul>
        <li>HTML & CSS basics</li>
        <li>JavaScript essentials</li>
        <li>Frontend projects</li>
        <li>Interactive UI components</li>
      </ul>
    </section>
  </main>

  <footer>
    <p>&copy; 2025 CodeLearn. All rights reserved.</p>
  </footer>

  <script src="script.js"></script>
</body>
</html>
quiz icon실력 점검

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

JavaScript in Action의 모든 레슨