The JavaScript alert() function is a function available on the global window object. It commands the browser to display a modal dialog with a message and an "OK" button.

Here's a basic example of usage:

alert("Hello world!");

// Which is quivalent to:
window.alert("Hello world");

Note that, when executed, the alert function will get the focus and prevent the user from interacting with the reset of the website until the modal gets dismisssed.

Examples using alert

1. Alert message on click

A very common use case for the alert fuction is to use it when filling a form and then trying to submit it by clicking a button.

Let's say we want to make sure the user is over 18 years old when filling the following form:

<form name="myForm" action="">
<label for="age">Age</label>
<input type="number" name="age" id="age" />
<button type="submit">Submit</button>

All we have to do is attach an event listener to the button, checking for the value of the input field and then displaying the modal with the alert function of JavaScript:

var checkAge = (e) => {
if(document.querySelector('#age').value < 18){

// Preventing the submit of the form

// Displaying the modal window
alert("You have to be older 18!");

// Listening to the click event on the button
document.querySelector('button').addEventListener('click', checkAge);

See the Pen on CodePen.

2. Alert box before closing the window

It's also a common practise in websites that require saving changes to display an alert message when the user tries to close the browser's window or tab.

To do this, we have to first detect when the user is about to close the window. We can achieve this in two different ways, but it's usually recommended to use event listeners when possible.

// Using event listeners
window.addEventListener("beforeunload", showDialog);

// Overwriting the window default property function
window.onbeforeunload = showDialog;

Now all we have to do is show them a dialog. But in this case, we won't be using the alert function for this scenario.

Unfortunately we can not customise the message that gets displayed on the dialog anymore. We still have to return a text for old browsers compatibility, but the message will most likely not get displayed on modern browsers. They'll show a default message telling the user that changes won't get saved.

So, here's how we tell the browser we want to show a message, but returning a string on the event function:

var showDialog = (e) => {
return 'Dialog text here.';
window.addEventListener("beforeunload", showDialog);

3. Alert box on page load

In some very specific cases, websites might want to show an alert message on page load. To do this all we need to do is fire the alert message on the <head> section of our HTML. This way, the alert will be shown before loading any elements on the page.

alert("Displayed before page loads");
Your page content.

4. Alert message using a variable

Using a variable to display different messages based on its content can also be done quite easily. Simply pass the variable to the alert method instead of a string text.

Here's an example:

var myVariable = 'I love alert boxes!!';

5. Alert a message requiring confirmation

Perhaps you want to show an alert that requires the visitors confirmation and that allows them too also cancel or ignore it by displaying a "Cancel" and an "OK" buttons. For these cases we will use the confirm function, which can be seen as a variant of the alert function.

The confirm function will just add a "Cancel" button on top of the "OK" one added by the alert method.

confirm('Do you want to continue?');

We can catch the visitor's decision by checking the result of the method. It will be true if the visitor clicks on "OK" and false otherwise.

if(confirm("Do you want to continue?")){
// continue heree

See the Pen on CodePen.

6. Alert a message showing input field

In some occassions we might want to capture the user input directly on the alert message. In this cases we will also move away from the alert function and use the alternative function prompt. This function creates the same dialog box but adds a text field to it and the "Cancel" button too.

It admits twoo parameters. The first one is the text to show on the dialog (for the input) and the second one is the default value for the input (if any).

// Showing a dialog box with a text input containing "Steve"
prompt("Enter your name, please:", "Steve");

// Showing a dialog box with ab empty text input.
prompt("Enter your name, please:");

See the Pen on CodePen.

7. Alerts with custom styles

In order to use your own custom alert modals we'll have to make use of JavaScript and CSS. The easiest, fastest and probably most reliable way to do it is by using external plugins instead of doing it by yourself.

One of the most used ones is SweetAlert2, or even its predecesor SweetAlert.

Here's an example of how a confirm alert dialog looks like when using this component:

var showConfirm = (e) => {
title: 'Error!',
text: 'Do you want to continue',
confirmButtonText: 'Yeap!'

document.querySelector('button').addEventListener('click', showConfirm);

As you can see there aren't huge changes in our code and the usage is quite straight away.

You can check more alert examples using this component on their website.

There are other dialog boxes plugins out there, so feel free to choose the one that fits your needs.