JavaScript: alert()
The alert() method shows a short message in a dialog and pauses the current script until the user closes it.
What you will learn
- How to display a message with
alert() - Why the dialog blocks script and browser interaction
- When a less disruptive interface is better
Minimal example
alert("Please check the required fields.");
alert("First line\nSecond line");The browser displays an OK button. JavaScript does not continue until the dialog is closed, so avoid showing alerts repeatedly or using them as the only way to explain a form error.
Common mistakes
- Do not use
alert()for every validation message; place an accessible explanation near the related input when possible. - Do not assume the dialog looks the same in every browser.
- Use
addEventListener()for event handling instead of putting large inline scripts in HTML.