Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Explain JavaScript text alert
The JavaScript alert() function is used to display a popup message to the user. It's a built-in browser method that creates a modal dialog box with a message and an "OK" button.
Syntax
alert(message);
Parameters
The alert() function accepts one parameter:
- message - A string that specifies the text to display in the alert box
Basic Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Alert Example</title>
</head>
<body>
<h1>JavaScript Text Alert</h1>
<button id="alertBtn">Show Alert</button>
<p>Click the button above to display an alert popup</p>
<script>
document.getElementById("alertBtn").addEventListener("click", function() {
alert("Hello! This is a JavaScript alert.");
});
</script>
</body>
</html>
Multiple Alert Examples
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiple Alerts</title>
</head>
<body>
<button onclick="simpleAlert()">Simple Alert</button>
<button onclick="numberAlert()">Number Alert</button>
<button onclick="multiLineAlert()">Multi-line Alert</button>
<script>
function simpleAlert() {
alert("This is a simple text alert!");
}
function numberAlert() {
let number = 42;
alert("The answer is: " + number);
}
function multiLineAlert() {
alert("Line 1\nLine 2\nLine 3");
}
</script>
</body>
</html>
Key Points
-
alert()blocks code execution until the user clicks "OK" - The alert box is modal - users cannot interact with the page until dismissed
- Use
for line breaks in alert messages - Alert boxes cannot be styled with CSS
- Modern web development often uses custom modals instead of alert()
Browser Compatibility
The alert() function is supported by all modern browsers and has been part of JavaScript since its early versions.
Conclusion
JavaScript's alert() function provides a simple way to display messages to users. While useful for debugging and simple notifications, consider using modern alternatives like custom modals for better user experience in production applications.
Advertisements
