alert() displays a modal message with an OK button. It is useful for small demonstrations and important one-off messages, but it interrupts interaction with the page until the user dismisses it.
alert("Hello");The original tutorial uses a button that calls a function and displays a string stored in a variable. The same facility is retained below with modern event handling.
const button = document.getElementById("showAlert");
button.addEventListener("click", () => {
const message = "Welcome to plus2net.com";
alert(message);
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Alert demo</title>
</head>
<body>
<button id="showAlert" type="button">Click here to display alert message</button>
<script>
const button = document.getElementById("showAlert");
button.addEventListener("click", () => {
const message = "Welcome to plus2net.com";
alert(message);
});
</script>
</body>
</html>The original second demo reads a text box and displays the entered value in an alert. That behavior is preserved.
DEMO window alert with message
<input type="text" id="t1">
<button type="button" id="showAlert">Click here to display alert message</button>
<script>
document.getElementById("showAlert").addEventListener("click", () => {
const message = document.getElementById("t1").value;
alert(message);
});
</script>Use alerts sparingly in production interfaces because they block the page. For normal validation or status feedback, an inline message near the relevant control is usually less disruptive.
For a two-choice modal, see confirmation before an action and the dedicated confirm tutorial.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| placidius | 03-05-2012 |
| this code has been useful to me, thank you very much for your sharing. | |