Dismissible banners
Part of the JavaScript in Action section of Coddy's HTML journey — lesson 9 of 27.
A dismissible banner is a notification or message bar that appears at the top (or bottom) of the page and can be closed by the user. These are often used to show important information, like cookie policies, announcements, or warnings. The key feature is the close (×) button that lets the user hide the banner without refreshing the page.
First, let's add the HTML structure:
<div class="banner" id="banner">
<p>This is an important announcement!</p>
<button id="closeBanner">X</button>
</div>Next, let's add some basic CSS to style our banner:
.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;
}Finally, add JavaScript to make the banner dismissible:
const banner = document.getElementById('banner');
const closeBtn = document.getElementById('closeBanner');
closeBtn.addEventListener('click', function() {
banner.style.display = 'none';
});
When the close button is clicked, the banner will disappear.
Challenge
EasyWe want the banner to disappear when the user clicks the close button.
- Add an event listener so that when the close button is clicked, a function will run.
- Inside this function, set the
displayproperty of the banner element tononeso it gets hidden.
Try it yourself
<!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">×</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>© 2025 CodeLearn. All rights reserved.</p>
</footer>
<script src="script.js"></script>
</body>
</html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.