How to Show a JavaScript Alert from a Button

A browser alert displays a short message using browser-controlled UI. Attach it to an explicit action so the user knows what caused it. Modern HTML does not need the old language="JavaScript" attribute or HTML comment wrappers around script code.

Create a runnable page

Save this as alert.html, open it and press Show message:

HTML
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Message example</title>
<button id="show-message" type="button">Show message</button>
<p id="status" role="status"></p>
<script>
const button = document.getElementById("show-message");
const status = document.getElementById("status");

button.addEventListener("click", () => {
  window.alert("The demonstration is ready.");
  status.textContent = "The alert call has returned.";
});
</script>
</html>

Under normal foreground interaction, the browser displays a message and waits for dismissal. The page then updates its status paragraph. The status deliberately says the call returned because browsers can suppress dialogs in some circumstances, so a return does not prove the user read the message.

Choose the right interaction

For routine updates, omit the alert call and set status.textContent directly. This keeps the interface usable and provides a live status region for assistive technology. Use text content rather than inserting untrusted HTML.

An alert is not a confirmation control because it does not return a yes/no decision. Do not use its appearance as evidence that a database save or network request succeeded. Await the operation, inspect its result, then display the appropriate message.

If a deployed page uses a Content Security Policy that blocks inline scripts, move the JavaScript into an allowed external file or apply the site's existing nonce mechanism. Do not weaken the policy just to reproduce this standalone demonstration.

References

Window: alert() method - Web APIs | MDN
window.alert() instructs the browser to display a dialog with an optional message, and to wait until the user dismisses the dialog.
https://developer.mozilla.org/en-US/docs/Web/API/Window/alert
Window.alert
EventTarget: addEventListener() method - Web APIs | MDN
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
EventTarget.addEventListener

Author: Herman Schoenfeld