Javascript close all alerts

Взаимодействие с пользователем: 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 .

Источник

Programmatically close alert() in Javascript [duplicate]

As far as I know you cannot close the javascript’s alert(); by code. You can try to use alternative notification method like modal window or something (so then if user is back online you can simply use jQuery function to hide/remove the modal box)., Why do we never learn cross validation in regular statistical textbooks? ,According to my knowledge Java Script Alert box cant be change or close programmatically. So you can use Jquery UI Dialog box or bootstrap model or something else. ,Connect and share knowledge within a single location that is structured and easy to search.

As far as I know you cannot close the javascript’s alert(); by code. You can try to use alternative notification method like modal window or something (so then if user is back online you can simply use jQuery function to hide/remove the modal box).

Answer by Cameron Cherry

window.setTimeout('alert("Message goes here");window.close();', 5000);

Answer by Lylah Whitehead

window.alert() instructs the browser to display a dialog with an optional message, and to wait until the user dismisses the dialog.,Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to dismiss the dialog., A string you want to display in the alert dialog, or, alternatively, an object that is converted into a string and displayed. ,BCD tables only load in the browser

Answer by Raymond Macdonald

Even then, if I call closeAlert() from the Javascript console, it does nothing except return the error:,The docs show you can close an alert by calling the aptly named closeAlert() from an alert button’s onclick event.,Successfully merging a pull request may close this issue.,However, I’d like an alert to be closed by pressing the Esc key, yet there seems to be something blocking the escape key press from reaching my custom keypress handler, even though all other key presses are being registered.

Cannot read property 'target' of undefined 

Answer by Kaleb Ellison

As mentioned previously you really can’t do this. You can do a modal dialog inside the window using a UI framework, or you can have a popup window, with a script that auto-closes after a timeout. each has a negative aspect. The modal window inside the browser won’t create any notification if the window is minimized, and a programmatic (timer based) popup is likely to be blocked by modern browsers, and popup blockers.,A sidenote: if you have an Alert(«data»), you won’t be able to keep code running in background (AFAIK). . the dialog box is a modal window, so you can’t lose focus too. So you won’t have any keypress or timer running. I guess you could open a popup window and call that a dialog box. I’m unsure of the details, but I’m pretty sure you can close a window programmatically that you opened from javascript. Would this suffice?,Ref: inspired by this answer, though that answer doesn’t work in modern Chrome anymore, but the Notification API does.

If you want it to close after 1s:

var notification = new Notification("Hi there!", ); setTimeout(function() , 1000); 

Answer by Dayana McCoy

If you’re building our JavaScript from source, it requires util.js. The compiled version includes this.,Enable dismissal of an alert via JavaScript:,Be sure you’ve loaded the alert plugin, or the compiled Bootstrap JavaScript.,To animate alerts when dismissing them, be sure to add the .fade and .show classes.

 
A simple primary alert—check it out!
A simple secondary alert—check it out!
A simple success alert—check it out!
A simple danger alert—check it out!
A simple warning alert—check it out!
A simple info alert—check it out!
A simple light alert—check it out!
A simple dark alert—check it out!

Answer by Rebecca Cobb

Easy to use and highly flexible! A jQuery plugin that provides great set of features like, Auto-close, Ajax-loading, Themes, Animations and more. This plugin is actively developed, I would love you have your suggestions. , alerts, confirms and dialogs in one. , NOTE : The $.confirm(), $.dialog() & $.alert() methods are alias of jconfirm(). All three methods indirectly call the jconfirm base function altering the provided options. , it is ideal to set this in jconfirm.defaults

via Bower:
Simply copy these links

$ bower install craftpip/jquery-confirm
$ npm install jquery-confirm

Answer by Felix Finley

A message with auto close timer Try me! swal(< title: 'Auto close alert!', text: 'I will close in 2 seconds.', timer: 2000 >) , Call the sweetAlert2-function after the page has loaded swal(< title: 'Error!', text: 'Do you want to continue', type: 'error', confirmButtonText: 'Cool' >) ,A message with a custom image and CSS animation disabled,Custom HTML description and buttons

Code:
alert('Oops! Something went wrong!')

Answer by Jeffrey Tapia

Description: Bind an event handler to the «dblclick» JavaScript event, or trigger that event on an element.,The dblclick event is only triggered after this exact series of events:,To bind a «Hello World!» alert box to the dblclick event on every paragraph on the page:,To trigger the event manually, call .dblclick() without an argument:

Источник

How TO — Alerts

Alert messages can be used to notify the user about something special: danger, success, information or warning.

Create An Alert Message

Step 1) Add HTML:

Example

If you want the ability to close the alert message, add a element with an onclick attribute that says «when you click on me, hide my parent element» — which is the container (class=»alert»).

Tip: Use the HTML entity » × » to create the letter «x».

Step 2) Add CSS:

Style the alert box and the close button:

Example

/* The alert message box */
.alert padding: 20px;
background-color: #f44336; /* Red */
color: white;
margin-bottom: 15px;
>

/* The close button */
.closebtn margin-left: 15px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
line-height: 20px;
cursor: pointer;
transition: 0.3s;
>

/* When moving the mouse over the close button */
.closebtn:hover color: black;
>

Many Alerts

If you have many alert messages on a page, you can add the following script to close different alerts without using the onclick attribute on each element.

And, if you want the alerts to slowly fade out when you click on them, add opacity and transition to the alert class:

Example

// Get all elements with >var close = document.getElementsByClassName(«closebtn»);
var i;

// Loop through all close buttons
for (i = 0; i < close.length; i++) // When someone clicks on a close button
close[i].onclick = function()

// Get the parent of var div = this.parentElement;

// Set the opacity of div to 0 (transparent)
div.style.opacity = «0»;

// Hide the div after 600ms (the same amount of milliseconds it takes to fade out)
setTimeout(function()< div.style.display = "none"; >, 600);
>
>

Tip: Also check out Notes.

Источник

Javascript close alert box

I want to be able to close an alert box automatically using javascript after a certain amount of time or on a specific event (i.e. onkeypress). From my research, it doesn’t look like that’s possible with the built-in alert() function. Is there a way to override it and have control over the dialog box that it opens?

Also, I don’t want an override that shows a hidden div as the alert. I need an actual dialog box.

Solution

As mentioned previously you really can’t do this. You can do a modal dialog inside the window using a UI framework, or you can have a popup window, with a script that auto-closes after a timeout. each has a negative aspect. The modal window inside the browser won’t create any notification if the window is minimized, and a programmatic (timer based) popup is likely to be blocked by modern browsers, and popup blockers.

OTHER TIPS

Appears you can somewhat accomplish something similar with the Notification API. You can’t control how long it is visible (probably an OS preference of some kind—unless you specify requireInteraction true), and it requires the user to click «allow notifications» (unfortunately), but here it is:

If you want it to close after 1s:

var notification = new Notification("Hi there!", ); setTimeout(function() , 1000); 

If you wanted to show it longer than the «default» you could bind to the onclose callback and show another repeat notification I suppose, to replace it.

Ref: inspired by this answer, though that answer doesn’t work in modern Chrome anymore, but the Notification API does.

no control over the dialog box, if you had control over the dialog box you could write obtrusive javascript code. (Its is not a good idea to use alert for anything except debugging)

I want to be able to close an alert box automatically using javascript after a certain amount of time or on a specific event (i.e. onkeypress)

A sidenote: if you have an Alert(«data»), you won’t be able to keep code running in background (AFAIK). . the dialog box is a modal window, so you can’t lose focus too. So you won’t have any keypress or timer running.

var alert = bootbox.alert('Massage') alert.show(); setTimeout(function(), 4000); 

I guess you could open a popup window and call that a dialog box. I’m unsure of the details, but I’m pretty sure you can close a window programmatically that you opened from javascript. Would this suffice?

The only real alternative here is to use some sort of custom widget with a modal option. Have a look at jQuery UI for an example of a dialog with these features. Similar things exist in just about every JS framework you can mention.

If you do it programmatically in JS it will be like reinventing the wheel. I recommend using a jQuery plugin called jGrowl

You can use label and set its fade in and out time for e.g Hide it initially and show on click. $(‘#div_Message’).fadeIn(500).delay(1000).fadeOut(1500);

window.setTimeout('alert("Message goes here");window.close();', 5000); 

Источник

Читайте также:  Python end перенос строки
Оцените статью