In this blog post, we will understand how we can add a click event to a button using a few different techniques.


Why Do You Need A Click Event?

Buttons in HTML perform an action.

This can be submitting a form, starting or stopping an operation, triggering a process, or just visually changing the website. All of the above happens when the user clicks a button.

HTML and Javascript together provide us the functionality where you can add buttons to the website and then use Javascript to trigger the button.


Adding A OnClick Event To A Button

Let's add a button to our HTML code and then write some Javascript to create an onClick event.

Using this onClick event we will perform different actions.


As you can see in the HTML above, we have created an HTML button and in the same line, we are using the onclick attribute that is available on the HTML element that we can use and write some Javascript code in it.

In the above example, we have used inline Javascript code.

We can also write the above example as below:


Here, we have extracted the inline Javascript and taken it out to it's own function.

Then we call the function from the onclick event on the HTML button.

Both the examples above perform the same exact operation.

The result is an alert box like this: