How to Create a Button Click Event in Vanilla JavaScript?

Estimated read time 1 min read

You can create a button click event in vanilla JavaScript using the onclick property. The onclick property allows you to specify a function that will be executed when the button is clicked.

Here’s an example of how to create a button click event:

<button id="myButton">Click Me</button>

<script>
  document.getElementById("myButton").onclick = function() {
    alert("Button was clicked");
  };
</script>

In this example, the document.getElementById() method is used to retrieve the button element from the DOM. The onclick property is then used to specify a function that will be executed when the button is clicked. The function displays an alert message when the button is clicked.

This will create a button that, when clicked, will display an alert message, demonstrating that the click event has been successfully attached to the button.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply