Create a Simple Notification Bar on Top of Page Using jQuery
Notification bars on top of a page is a feature to display important messages to catch a website visitor’s attention. There are plenty of plugins available to display notification bars, but it’s not advisable to use a jQuery plugins if the same task can be completed via simple jQuery code, as adding a plugin will consume bandwidth. So in this post, let’s see how to create notification bar on top of the page using custom jQuery.
The notification bar will have a close button along with sample message. Clicking on close button will hide the notification bar. And there also exists another link to display the notification bar again if it’s hidden. Below is the HTML used for creating navigation bar along with all required buttons.
<div id="dvNotify" class="notification">
<label>Sample notification message.</label>
<a href="#" id="btnClose">[x]</a>
</div>
<div style="text-align:center;">
<a href="#" id="btnShow">Show Notification</a>
</div>
As we need to display the notification bar on top of the page with absolute positioning, here is the CSS used for the same.
.notification {
background-color: lightYellow;
color: red;
font-size: 16pt;
position: absolute;
width: 100%;
top: 0px;
left: 0px;
text-align: center;
padding: 10px;
}
And finally jQuery code to show and hide the notification bar.
$(function() {
$("#btnClose").click(function(evt) {
$("#dvNotify").slideUp('slow');
});
$("#btnShow").click(function(evt) {
$("#dvNotify").slideDown('slow');
});
})
And here is the demo.
<script async src="//jsfiddle.net/ftu67cff/embed/result/dark/"></script>
When page is loaded, the notification bar will always be displayed. If you want to hide it on page load and want to show it on button click, then you need to add following line to jQuery code.
$(function() {
$("#dvNotify").hide();