- JavaScript Alert [Examples And Usage]
- Examples using alert
- 1. Alert message on click
- 2. Alert box before closing the window
- 3. Alert box on page load
- 4. Alert message using a variable
- 5. Alert a message requiring confirmation
- 6. Alert a message showing input field
- 7. Alerts with custom styles
- Related articles
- Взаимодействие с пользователем: alert, prompt, confirm
- alert
- prompt
- confirm
- Особенности встроенных функций
- Резюме
JavaScript Alert [Examples And Usage]
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">Agelabel>
input type="number" name="age" id="age" />
button type="submit">Submitbutton>
form>
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
e.preventDefault();
// 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);
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 section of our HTML. This way, the alert will be shown before loading any elements on the page.
head>
script>
alert("Displayed before page loads");
/script>
/head>
body>
Your page content.
/body>
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.
var myVariable = 'I love alert boxes!!';
alert(myVariable);
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
>
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:");
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) =>
e.preventDefault();
Swal.fire(
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.
Related articles
Взаимодействие с пользователем: alert, prompt, confirm
Материал на этой странице устарел, поэтому скрыт из оглавления сайта.
Более новая информация по этой теме находится на странице https://learn.javascript.ru/alert-prompt-confirm.
В этом разделе мы рассмотрим базовые UI операции: alert , prompt и confirm , которые позволяют работать с данными, полученными от пользователя.
alert
alert выводит на экран окно с сообщением и приостанавливает выполнение скрипта, пока пользователь не нажмёт «ОК».
Окно сообщения, которое выводится, является модальным окном. Слово «модальное» означает, что посетитель не может взаимодействовать со страницей, нажимать другие кнопки и т.п., пока не разберётся с окном. В данном случае – пока не нажмёт на «OK».
prompt
Функция prompt принимает два аргумента:
result = prompt(title, default);
Она выводит модальное окно с заголовком title , полем для ввода текста, заполненным строкой по умолчанию default и кнопками OK/CANCEL.
Пользователь должен либо что-то ввести и нажать OK, либо отменить ввод кликом на CANCEL или нажатием Esc на клавиатуре.
Вызов prompt возвращает то, что ввёл посетитель – строку или специальное значение null , если ввод отменён.
Единственный браузер, который не возвращает null при отмене ввода – это Safari. При отсутствии ввода он возвращает пустую строку. Предположительно, это ошибка в браузере.
Если нам важен этот браузер, то пустую строку нужно обрабатывать точно так же, как и null , т.е. считать отменой ввода.
Как и в случае с alert , окно prompt модальное.
var years = prompt('Сколько вам лет?', 100); alert('Вам ' + years + ' лет!')
Второй параметр может отсутствовать. Однако при этом IE вставит в диалог значение по умолчанию «undefined» .
Запустите этот код в IE, чтобы понять о чём речь:
Поэтому рекомендуется всегда указывать второй аргумент:
confirm
confirm выводит окно с вопросом question с двумя кнопками: OK и CANCEL.
Результатом будет true при нажатии OK и false – при CANCEL( Esc ).
var isAdmin = confirm("Вы - администратор?"); alert( isAdmin );
Особенности встроенных функций
Конкретное место, где выводится модальное окно с вопросом – обычно это центр браузера, и внешний вид окна выбирает браузер. Разработчик не может на это влиять.
С одной стороны – это недостаток, так как нельзя вывести окно в своём, особо красивом, дизайне.
С другой стороны, преимущество этих функций по сравнению с другими, более сложными методами взаимодействия, которые мы изучим в дальнейшем – как раз в том, что они очень просты.
Это самый простой способ вывести сообщение или получить информацию от посетителя. Поэтому их используют в тех случаях, когда простота важна, а всякие «красивости» особой роли не играют.
Резюме
- alert выводит сообщение.
- prompt выводит сообщение и ждёт, пока пользователь введёт текст, а затем возвращает введённое значение или null , если ввод отменён (CANCEL/ Esc ).
- confirm выводит сообщение и ждёт, пока пользователь нажмёт «OK» или «CANCEL» и возвращает true/false .