How to Create an Alert Message with a Button Click in JavaScript?

Estimated read time 2 min read

To create an alert message with a button click in JavaScript, you can use the addEventListener() method to attach an event listener to a button element, and then use the alert() function to display the message. Here’s an example code snippet that demonstrates how to create an alert message with a button click in JavaScript:

<button id="myButton">Click me!</button>

<script>
  const button = document.getElementById("myButton");
  button.addEventListener("click", () => {
    alert("Hello, world!");
  });
</script>

In this code, the HTML markup creates a button element with an ID of “myButton”. The JavaScript code then uses the document.getElementById() method to get a reference to the button element, and the addEventListener() method to attach a “click” event listener to it.

The event listener is an arrow function that simply calls the alert() function with the message “Hello, world!”. When the button is clicked, the event listener is triggered, which in turn displays the alert popup with the message.

You can customize the message displayed in the alert popup by modifying the string passed as an argument to the alert() function. You can also add more complex logic to the event listener function to perform other actions when the button is clicked, such as changing the text or style of other elements on the page.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply