Toast message
Part of the JavaScript in Action section of Coddy's HTML journey — lesson 8 of 27.
A toast message is a small notification that briefly appears on the screen to give feedback to the user. It usually fades out after a few seconds.
Create a basic HTML structure:
<div class="container">
<button id="showToast">Show Toast</button>
<div id="toast" class="hidden">This is a toast message!</div>
</div>Add some CSS to style the toast. We use two classes: .hidden to keep it invisible, and .show to make it appear.
.toast {
position: fixed;
bottom: 20px;
left: 50%;
background-color: #333;
color: white;
padding: 15px 25px;
}
.show {
opacity: 1;
}
.hidden {
display: none;
}Now add JavaScript to show and hide the toast:
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);
});This code makes the toast visible when the button is clicked, and automatically hides it after 3 seconds.
Challenge
EasyYour goal is to make the toast look nice and ready for appearing/disappearing.
- Place the toast message in the center at the bottom of the page using
position: fixedwithbottomandleft. - Give it a background color and change the text color to make it readable.
- Add some padding so the message isn’t cramped.
- Make the corners look smooth.
- Set its opacity to 0 so that it is hidden by default (before the JavaScript shows it).
Try it yourself
<!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>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.