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.
Alerts on Android can be dismissed by tapping outside of the alert box. It is disabled by default and can be enabled by providing an optional Options parameter with the cancelable property set to true i.e.
One of the nice things about the built-in JavaScript alert is that - unlike virtually anything else in JavaScript - it's synchronous. It's completely blocking, and no other code will execute until it's been dismissed.
Alert Box. An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed.
One useful function that's native to JavaScript is the alert() function. This function will display text in a dialog box that pops up on the screen. Before this function can work, we must first call the showAlert() function. JavaScript functions are called in response to events.
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.
Appears you can somewhat accomplish something similar with the Notification API. You can't control how long it stays visible (probably an OS preference of some kind--unless you specify requireInteraction true, then it stays up forever or until dismissed or until you close it), and it requires the user to click "allow notifications" (unfortunately) first, but here it is:
If you want it to close after 1s (all OS's leave it open 1s at least):
var notification = new Notification("Hi there!", {body: "some text"}); setTimeout(function() {notification.close()}, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With