This article was originally published on my personal blog.
You've probably seen the confirm dialog being used whenever you're making edits to data on a website. Whether you're filling out a form, editing a document, or just making any kind of changes that require you to save your progress, you'll probably see an alert when you try to leave the page to alert you that your progress will not be saved if you leave.
The confirm dialog is a simple yet necessary user experience strategy that shows your users that you understand them.
In this tutorial, we'll learn how to use the confirm
function to confirm a user's actions. We'll also see how to show a confirm dialog before the user leaves the page based on whether the user saved their progress or not.
Use confirm()
If you want to show a dialog that confirms the user's actions at any point, you can use window.confirm
.
This function accepts one optional parameter, which is the message to show to the user. If the parameter is not provided, no message will be shown. Then, it returns a boolean based on what the user chooses. If the user "OK", it returns true, else it returns false.
For example, we'll show a button that will trigger the confirm dialog on click:
<button id="confirmTrigger">Show Confirm</button>
<p id="confirmResult"></p>
Inside p
we'll show the result based on what the user chooses.
Then, in our JavaScript we'll add an event listener to the button's click event:
const button = document.getElementById('confirmTrigger');
const confirmResult = document.getElementById('confirmResult');
button.addEventListener('click', function (e) {
if (window.confirm('Do you confirm?')) {
confirmResult.innerText = 'Yes';
} else {
confirmResult.innerText = 'No';
}
});
This will show a confirm dialog with the text "Do you confirm?".
If the user presses OK, "Yes" will be displayed in the p
element.
Else, "No" will be displayed in the p
element:
That's it! Using window.confirm
, you can confirm a user's actions at any given point on your website.
Show a Confirm Dialog When a User Leaves a Page
The most famous usage for confirm dialogs would be to warn the user before they leave or refresh the page, usually because they haven't saved their progress.
To implement this, you don't need to use confirm()
. You need to add a listener to the window's beforeunload
event.
Add onbeforeunload Listener
To add a listener to the beforeunload
event, you can either assign a function to window.onbeforeunload
:
window.onbeforeunload = function (e) {
//do something
}
or using window.addEventListener
:
window.addEventListener('beforeunload', function (e) {
//do something
}
Although this is the recommended method, it seems that onbeforeunload
works and is supported more.
Show a Confirm Dialog Before Leaving the Page
To show the confirmation dialog before the user leaves the page, the event listener for beforeunload
the event should return a non-empty string.
If the listener does not return any value or returns an empty string, no confirm dialog will be shown to the user.
When the Confirm Dialog is Not Shown
To avoid unwanted pop-ups, browsers generally will not display the confirm dialog on beforeunload
if the user has not interacted with the page.
For example, let's say we have the following page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Confirm Dialog</title>
</head>
<body>
<script>
window.onbeforeunload = function (e) {
return 'Are you sure?';
}
</script>
</body>
</html>
This page has no elements (or any elements, actually) that the user can interact with, yet it requests to show a confirm dialog when the user leaves the page.
If you test this code on any modern browser, you'll see that the confirm dialog will not be shown.
Example
We'll see how to show a confirm dialog only when the user hasn't saved their progress.
First, we'll show a text input so the user enters their name. We'll also show a button for them to save, and a p
element where we'll show the value they entered when they save:
<h1>Hello there!</h1>
<input type="text" name="name" placeholder="Name" />
<button>Save</button>
<p></p>
Then, in JavaScript, we'll first declare variables for each of these elements:
const button = document.querySelector('button');
const input = document.querySelector('input');
const p = document.querySelector('p');
let saved = false;
Note that we also declared the variable saved
, initially set to false
. In a real use-case scenario, you'll probably manage whether the user saved their progress by checking if the data they entered has been saved on the server. To simplify the tutorial, we're just using this variable to manage whether the progress has been saved or not.
We'll add an event listener to button
's click event. In this event listener, we'll change saved
to true
, and we'll change the text of p
to the value of input
:
button.addEventListener('click', function (e) {
p.innerText = input.value;
saved = true;
input.value = "";
});
We'll also add an event listener to the input
's keypress
event to change saved
to false when the user makes changes to the input
, even if they already saved their progress previously:
input.addEventListener('keypress', function (e) {
saved = false;
});
Finally, we'll add the event listener for onbeforeunload
, which will show the confirmation dialog if the user has not saved their progress:
window.onbeforeunload = function (e) {
if (!saved) {
return 'Are you sure?';
}
};
Note that although we return a string, this string will not actually be shown a custom message to the user. Custom messages used to be supported in Chrome until version 51, Firefox until version 44, Safari until version 9, but is still supported in IE.
Let's try our example. First, open this page. You'll see a heading, input, and a button.
Let's first try leaving the page before interacting with any of the input elements. According to our code, if saved
is false, which is its initial value, the confirm dialog should show.
However, if you try leaving the page before interacting with the elements, you'll see that the confirm dialog will not show as explained before.
Now, try to make type something into the input, and before clicking Save, exit, or refresh the page. Then, a confirmation dialog will show to warn you before you leave the page:
If you try to enter in the input, click save, then leave the page, the confirm dialog will not show.
If you try to enter a value in the input, click save, then try to enter a value in the input again, you'll see that the confirmation dialog will be shown again.
With this example, we're able to manage the saved state and warn the user before leaving the page without saving their progress.
Conclusion
As users may not be aware sometimes that they need to save their progress, or because they can make mistakes, it's important to show them a confirm dialog before they leave the page.
Using the beforeunload
event facilitates showing the confirm dialog before the user leaves or reloads the page. To show the confirm dialog at any other point, you can use confirm()
instead.
Top comments (0)