How To Use Window Alert Method In JavaScript With Example

admin_img Posted By Bajarangi soft , Posted On 30-09-2020

In Java script we have alert() method which displays an alert box with a specified message and an OK button so today we are going to discuss about how to use alert method in java script

How To Use Window Alert Method In JavaScript With Example

The alert() method displays an alert box with a specified message and an OK button.

An alert box is often used if you want to make sure information comes through to the user.

The alert box takes the focus away from the current window, and forces the browser to read the message. Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed.

Syntax and Usage

alert(message)
 

Parameter Values

Parameter           Type           Description
message             String         Optional. Specifies the text to display in the alert box, or an object converted into a 
                                   string and   displayed.


Example(1)
<button class="btn btn-primary" onclick="get_alert()">Click it</button>

<script>
    function get_alert() {
        alert("Hello! I am an alert box!");
    }
</script>

In above example when you click button it will display an alert box.

Example(2)
<button class="btn btn-primary" onclick="get_alert()">Try it</button>

<script>
    function get_alert() {
        alert("Hello\nHow are you?");
    }
</script>

In above example when you click button it will demonstrate line-breaks in an alert box.


Example(3)
<button class="btn btn-primary" onclick="get_location()">Try it</button>

<script>
    function get_location() {
        alert(location.hostname);
    }
</script>

In above example when you click button it will alert the hostname of the current URL.

Complete Code For Window Alert Method In JavaScript With Example
<!DOCTYPE html>
<html>
<head>
    <title>Use Window Alert Method In JavaScript With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
    h1 {
        color: red;
    }
</style>
<body>
<div class="container">
    <br>
    <div class="text-center">
        <h1>Use Window Alert Method In JavaScript With Example</h1>
    </div>
    <br>
   <div class="well">
       <button class="btn btn-info" onclick="max_function()">Click it</button>
       <h2 id="h2" style="direction:rtl">Welcome to Bajarangisoft To Learn More About JAVASCRIPT</h2>
       <button class="btn btn-info" onclick="get_location()">Click it</button>
   </div>
</body>
</html>
<script>
    function max_function() {
        alert("Hello! I am an alert box!");
    }
    function get_location() {
        alert(location.hostname);
    }
</script>

Related Post