Making a yes no alert in Javascript
Published
Sometimes you need to go all the way and stop everything while you make sure the user is aware of the effects of what he’s doing. I’m sure you’ve already seen this happen while trying to close gmail while other tabs still have open emails. You get a prompt asking for confirmation, warning you about the consequences.
Why should you use a yes no alert?
First off, remember that a good design is one that stays out of the user’s way. You do not want to be prompting your user with an invasive alert at every step of their journey on your website.
Making an alert should be reserved for specific use cases, most often when dealing with destructive side-effects that aren’t clearly linked to the action the user is undertaking. One valid example of such a usage would in a text editor. By closing the window, the user would lose all the content he’s written since the last backup. By hijacking the navigation process, we are able to prevent such an outcome.
How do you create a yes no alert?
Such an alert is actually quite simple to implement as it uses the browser’s built-in confirm function. A barebones implementation would look like this:
// confirm gives us a boolean that matches the user's response
const confirmed = confirm('Is this really what you want to do?')
// We can then act on confirmed
if (confirmed) {
// do the action
} else {
// user canceled
}
I’ve put together an example yes no alert using Javascript and Svelte, try it out 👇
And here’s the actual code. We’re using a string template to inform the user of how many unread mails he’s going to delete.
let count = 6;
function alertFunction() {
const confirmed = confirm(`Do you want to delete ${count} unread mails?`);
if (confirmed) {
count = 0;
}
}
Bonus: displaying an alert when closing a tab or a window using Javascript
While quite similar to the previous yes no alert, the behaviour of this one is quite different. You’ll need to add a listener to the window’s “beforeunload” event and act on that event. Don’t forget to use preventDefault to prevent the regular execution of the event (which would just close the window) and manually set the event’s return value to an empty string.
window.addEventListener('beforeunload', (event) => {
event.preventDefault();
event.returnValue = '';
});
Be advised that this alert can’t be customized in any way and that the user will still be able to leave the website if he so desires.