There are two ways you can call a function when a button is clicked:
Let’s discuss both methods.
Method 1: Using the onclick attribute
The onclick
attribute is a part of the event attributes. It can be used on any HTML element and fires when the user clicks on the element.
You can assign any JavaScript function to the onclick
attribute. This assigned function will be fired up as soon as the user clicks on the element.
See the following example where we have assigned a custom function sayHi()
which will be called as soon as the button is clicked:
<button onclick='sayHi()'>Click Me</button>
And here is the related JavaScript code with a live example:
Example:
// Fires as soon as the button is clicked function sayHi(){ alert('Hi there'); }
Method 2: Using the addEventListener()
In this approach, we first fetch the element using any DOM method such as getElementById()
or querySelector()
, etc.
After fetching the element, we add an event listener to it using the built-in addEventListener() method. The addEventListener() method can listen to several mouse events such as click, dblclick, keydown, keyup, etc.
The addEventListener() method needs two parameters. First, the mouse event such as click, dblclick, etc. And the Second parameter is the function that will be called on the mouse event. This function can be a callback or a normal function.
See the following example where we have added an event listener which will call the function sayHi()
as soon as the button is clicked:
Example:
const button = document.getElementById('btn'); button.addEventListener('click', sayHi); // Fires on the button click function sayHi(event){ alert('Hi there'); }
Thanks for reading.