Create a WordPress notification bar with Javascript (without using a plugin)

A simple way to display a notification bar in WordPress is using a plugin such as Top Bar. There is also a premium version: Top Bar PRO which gives you access to some additional features: allow users to close the Top Bar, choose an initial state, add a bottom border, set a time before the Top Bar appears, bottom positioning, user visibility settings (only for guests or registered users), change the font-size…

WordPress Top Bar plugin

If you do not want to use a plugin, you can display a notificaiton bar by referring to “How to Create a WordPress Notification Bar Without a Plugin” which offers a jQuery script.

I converted it to a javascript script with a close button.

The Javascript code:

<script>
window.onload=function() //executes when the page finishes loading
{
setTimeout(func1, 2500);
};
function func1()
{
var el = document.getElementById('dabar');
el.innerHTML = '<button id="closexButton" onclick="document.getElementById(\'dabar\').style.display=\'none\'" ></button>Message to show in the notification bar'; // Add HTML code as you wish
el.className = 'showtopbar';
}
</script>

HTML – add the following line to footer.php:

<div id="dabar" class="hide_on_mobile hideonload"></div>

CSS code:

/* top-bar */
#dabar{
background: #2d2d2d; // Change the background color as you wish
color: #fff; // Change the font color
font-size:16px;
position: fixed;
z-index:1;
bottom: 0px; // if you want to display the notification bar at the top of the site, change it to top: 0px;
left: 0px;
width: 100% !important;
padding: 10px 0px;
text-align: center;}
#dabar a {color: #ffffff; border-bottom: 1px dotted;}

@media only screen and (max-width:783px) {
.hide_on_mobile {
display: none !important;} // Hide the notifcaiton bar on mobile devices
}

#closexButton {
display: inline;
float: right;
position: absolute;
right: 10px;
top: 13px;
height: 20px;
width: 20px;
cursor: pointer;
background: url(close button icon url);
}

#tpbr_calltoaction {
background: #f92c8b !important;
display:inline-block;
padding:2px 10px 2px;
color:white;
text-decoration:none;
margin: 0px 20px;
border-radius:3px;
}

The notification bar will be shown at the bottom of the site. (If you change “bottom: 0px” to “top: 0px”, it will be shown at the top of the site.)

It may not work properly depending on the theme you are using.

I am not good at Javascript. If there is anything that needs to be changed, please let me know.

Related Posts

Leave A Reply

Your email address will not be published.