Open In App

How to use the alert() method in JavaScript ?

Last Updated : 23 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to use the alert() method in JavaScript. The alert() method is used to show an alert box on the browser window with some message or warning. We can use it as a message or as a warning for the user.

Approach:

  • To show an alert on the browser window, we make a button. When we click on the button, a click event listener is called that calls a function.
  • In that function, we use the alert() method that contains a message for the user.
  • When we click the button, the alert window will pop up on the browser window that contains a message or warning with a button. 
  • Then you have to click the OK button so that the alert box can be closed.

Syntax:

alert(message/warning);

Below is the implementation of the above approach:

Example: This example shows the use of the above-explained approach.

HTML




<!DOCTYPE html>
 
<html lang="en">
 
<head>
    <style>
        body {
            /* path of the image */
            background-image: url(gfg_complete_logo_2x-min.png);
 
            /* Image is always centered*/
            background-position: center center;
 
            /* set the image fixed to the viewport */
            background-attachment: fixed;
 
            /* Not repeat image */
            background-repeat: no-repeat;
 
            /* Set background size auto */
            background-size: auto;
        }
    </style>
</head>
 
<body>
    <div style="margin-left: 500px; margin-top: 300px;">
        <button style="font-size: 20px;" class="btn" onclick="fun()">
            click me
        </button>
    </div>
 
    <script>
        function fun() {
            alert("Welcome on gfg!");
        }
    </script>
</body>
 
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads