JavaScript Alert ⚠💀 Boxes and Customized Alert Banners 🚩 [Tutorial]

alert-dialog-messagesThere are times in many application's life cycle where you need to interrupt the user with a message. These can be alerts, warning or informational. Browsers have native modal dialogs you can display using JavaScript to alert users to these important messages.

The JavaScript alert, confirm and prompt methods display dialogue boxes that pop up and take focus away from the page and forces the user to read the message.

You should only use these dialogs when absolutely necessary. Too many alerts and users will be upset.

Browsers have also started offering users the ability to block additional prompts. They do this because too many spammy sites abuse these native dialog options because they block all interactions, including navigation.

While native dialogs can be a proper tool, you are not limited to the native options, you can also create your own alert and informational pop-ups using CSS and some simple JavaScript.

When to Use Alerts and Warning Popups

JavaScript alerts are ideal for the following situations:

  • If you want to be absolutely sure they see a message before doing anything on the website.
  • You would like to warn the user about something.
  • Inform the user about an update.
  • An error has occurred and you want to inform the user of the problem.
  • When asking users for confirmation of some action.

There are also two ways you can provide in application messaging to users, as a dialog or as a banner overlay. You could also display an inline message, but I think that has more to do with form validation and instructions which I will cover in a separate post.

Using the JavaScript alert, prompt and info Dialog Functions

The native JavaScript alert, confirm and prompt dialogs are pretty easy to use.

The alert method has a single parameter, message, which is rendered in the middle of a dialog.

 alert("This is an Alert Dialog"); 

chrome-javascript-alert-dialog

ms-edge-alert-dialog

firefox-alert-dialog

The alert dialog is good when you just need to convey something important to the user. But if you need to collect a true/false answer you need to use the confirm dialog.

 confirm("This is an Confirm Dialog"); 

It also has a single parameter, a string containing the message or question you need to ask the user. Unlike the alert method the confirm method returns either true or false based on the user's response.

chrome-confirm-dialog

ms-edge-confirm-dialog

firefox-confirm-dialog

The last native prompt dialog you can display is the input dialog. This is where you can ask a question or just state something where you need an actual response from the user.

 prompt("This is an Prompt Dialog", "Please Provide a Response..."); 

This operates similarly to the confirm dialog, except it collects a text input from the user. It also has an optional second parameter where you can supply a default value or the equivalent of placeholder text.

chrome-prompt-dialog

ms-edge-prompt-dialog

firefox-prompt-dialog

These native functions have been around forever and make prompting the user for input or just conveying a message simple. They also natively keep the user from doing anything else with the browser, which honestly causes me more frustration than I would like.

The finally negative to these native JavaScript alert dialogs is they cannot be styled or customized. I intentionally inserted screenshots from Chrome, Edge and FireFox to show how different each browser renders these dialogs.

If you need to provide a consistent look in your application you will need to provide your own alert dialog alternatives using HTML, CSS and a little JavaScript.

Making a Custom Alert, Prompt and Info Dialog using JavaScript and CSS

There are literally hundreds of available plugins and framework extensions to help you display informational messages to users. Bootstrap has a series of components with a hard jQuery dependency that can serve as a good model.

However, I will demonstrate how you can achieve the same without an extra 150kb of JavaScript so your pages load faster and are much easier to maintain.

Again the main advantage to using a custom alert mechanism is you can customize the experience to be consistent with your branding and application asthetics. You will loose the ability to completely block all other browser actions, which I don't consider to be a bad thing.

There are two common ways to display messages to users, as a banner, typically rendered along one of the window sides or as a modal dialog. I will start with displaying a simple banner with a close button first.

A Simple Message Banner

This technique involved a combination of custom HTML, CSS and a little intermediate JavaScript. First the markup.

Instead of keeping the markup in the main DOM tree I like to use a markup template using an old school trick using a script tag. Instead of the script tag being a JavaScript element, the element's type is set to something other than the traditional 'application/javascript'.

For a generic template like I am demonstrating here I use x-template. This keeps the browser from trying to parse the element's content as a script. In fact it just skips parsing the elment all together. But you can still select the element, so I always ad an id attribute, banner-template here I can use to select the content.

banner-template-script-element

The banner needs to have an acceptable style applied. To keep things simple I chose to use the Bootstrap component as a reference because it is very simple. You can adjust the styles to meet your requirements.

 .banner { position: absolute; z-index: 9999; padding: .75rem 1.25rem; margin-bottom: 1rem; border: 1px solid transparent; border-radius: .25rem; display: none; } .banner.active { display: block; } .banner-bottom { left: 0; right: 0; bottom: 10px; } .banner-top { left: 0; right: 0; top: 10px; } .banner-right { right: 10px; bottom: 10%; min-height: 10vh; } .banner-left { left: 10px; bottom: 10%; min-height: 10vh; } .alert-primary { color: #004085; background-color: #cce5ff; border-color: #b8daff; } .banner-close { position: absolute; right: 1.5%; } .banner-close:after { position: absolute; right: 0; top: 50%; content: 'X'; color: #69f; } 

In this demonstration I am rendering the banner at the top of the window. But I have included rules to position it at the bottom and sort of at the bottom along the each side you can also use.

In this case the banner has a sky blue background with dark blue font. The close button is a span, absolutely positioned within the banner's right-hand side.

I used the close button element's :after psuedo element to apply an 'X'. You can use the psuedo element's content property to use what ever character or custom font glyph you want.

I added a z-index of 9999 to make the banner overlay anything on the screen, but the DOM insertion method I use should make it the last element in the DOM tree. This should also make it overlay all other elements.

You don't have to overlay your content, you may also want to cause it to push the content down, etc. This just requires a little extra CSS to affect your layout.

You may also want to add some simple transitions to make the banner fade in and out as well as slide into view. Again this example should just be a simple base for you to start your custom journey.

Next I add JavaScript to bind a callback to the alert button, used as the means to trigger the alert banner.

 var simpleAlert = document.querySelector(".simple-alert"); simpleAlert.addEventListener("click", function (e) { e.preventDefault(); injectTemplate(getBannerTemplate()); var btnClose = document.querySelector(".banner-close"); btnClose.addEventListener("click", function (closeEvt) { var banner = document.querySelector(".banner"); banner.parentNode.removeChild(banner); }); }); 

Again the click event is used to initiate the custom alert routine. This time some helper methods are used to grab the banner template and inject it in the DOM.

This technique is based on the createDocumentFragment insertion method I described in a previous article.

custom-banner-alert-overlay

Once the banner is inserted in the document you need to bind an event handler for the close element, represented with an 'x' on the banner's right-hand side.

The dynamic template insertion technique works great to avoid complex routines to keep track of event bindings, etc. Each time it is inserted you get a clean slate and can avoid unwanted memory leaks, etc.

When the close button is clicked it destroys the banner by removing it from the DOM.

I will add another article to extend this topic to custom modal dialogs in the near future so please follow my Twitter to know when that is added.

Summary

There are many options to interrupt the user with important messages about the application flow. There are native alert dialogs you can prompt using JavaScript or craft your own using CSS and HTML. Just make sure you don't abuse the power to display messages to the user.

You can access the source code on GitHub.

Share This Article With Your Friends!

We use cookies to give you the best experience possible. By continuing, we'll assume you're cool with our cookie policy.

Install Love2Dev for quick, easy access from your homescreen or start menu.

Googles Ads Bing Pixel LinkedIn Pixel