Menu
Coddy logo textTech

토스트 메시지

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

토스트 메시지는 사용자에게 피드백을 제공하기 위해 화면에 잠시 나타나는 작은 알림입니다. 보통 몇 초 후에 서서히 사라집니다.

기본 HTML 구조를 생성합니다:

<div class="container">
    <button id="showToast">Show Toast</button>
    <div id="toast" class="hidden">This is a toast message!</div>
</div>

토스트의 스타일을 지정하기 위해 CSS를 추가합니다. 보이지 않게 유지하는 .hidden과 나타나게 만드는 .show라는 두 가지 클래스를 사용합니다.

.toast {
    position: fixed;
    bottom: 20px;
    left: 50%;
    background-color: #333;
    color: white;
    padding: 15px 25px;
}
.show {
    opacity: 1;
}
.hidden {
    display: none;
}

이제 토스트를 표시하고 숨기기 위한 JavaScript를 추가합니다:

const showToastBtn = document.getElementById('showToast');
const toast = document.getElementById('toast');

showToastBtn.addEventListener('click', function() {
    toast.classList.remove('hidden');
    toast.classList.add('show');

    setTimeout(function() {
        toast.classList.remove('show');
        toast.classList.add('hidden');
    }, 3000);
});

이 코드는 버튼을 클릭하면 토스트를 표시하고, 3초 후에 자동으로 숨깁니다.

challenge icon

챌린지

쉬움

여러분의 목표는 토스트 메시지를 보기 좋게 만들고 나타나거나 사라질 준비를 하는 것입니다.

  1. position: fixedbottom, left를 사용하여 토스트 메시지를 페이지의 하단 중앙에 배치하세요.
  2. 배경색을 지정하고 텍스트 색상을 변경하여 읽기 쉽게 만드세요.
  3. 메시지가 답답해 보이지 않도록 패딩(padding)을 추가하세요.
  4. 모서리를 부드럽게 만드세요.
  5. 기본적으로 숨겨져 있도록(JavaScript가 표시하기 전까지) opacity를 0으로 설정하세요.

직접 해보기

<!DOCTYPE html>
<html>
<head>
  <title>Toast Notification Example</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header>
    <h1>My Profile Settings</h1>
  </header>

  <main>
    <p>Update your profile and save changes. A toast message will confirm your action.</p>
    <button id="showToast">Save Changes</button>
  </main>

  <!-- Toast -->
  <div id="toast" class="toast hidden">✅Your changes have been saved!</div>

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

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

JavaScript in Action의 모든 레슨