Get Alert on Button Click in a Class using JavaScript



An alert in JavaScript is a dialog box that is displayed to the user when some important information or warnings needs to be notified. It may contain a message along with OK button. When you click on the OK button, it will dismiss the dialog.

Clicking a button triggers an event handler which invoke a function that instructs the browser to display a dialog with a message. In this article, we will explore a few ways to get an alert to appear when user click on a button.

For example, click on the button given below to get an alert ?

Using Inline EventListener

In this approach, we directly embed the EventListener into HTML elements. This type of EventListener starts with the "on" prefix. Here, we use the onclick() event to get an alert on clicking a button.

Example

A JavaScript program that uses inline EventListener to display an alert is as follows ?

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initialscale=1.0">
   <title>Alert</title>
</head>
<body>
   <button onclick="alert('Demo Alert Message')">Click Button</button>
</body>
</html>

On running the above code, a button will appear clicking on which an alert window will pop up.

Using DOM EventListener

Here, we use the addEventListener() method to associate an event handler, an alert in this case. When we use this method, the JavaScript code would be separated from the HTML markup.

Example

Let's see the practical demonstration ?

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initialscale=1.0">
   <title>Document</title>
</head>
<body>
   <button class="clickTheButton">Click to get an alert</button>
   <script>
      for (var clickButton of
      document.getElementsByClassName("clickTheButton"))
      clickButton.addEventListener("click", alertMeessage);
      function alertMeessage() {
         alert("You have clicked the button");
      }
   </script>
</body>
</html>

When you click on edit and run, a button will be shown. On clicking that button, alert will be displayed.

Updated on: 2024-10-04T14:51:12+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements