JavaScript – Call Function on Button Click
There are two methods to call a function on button click in JavaScript. They are
Method 1: Use addEventListener() Method
- Get the reference to the button. For example, using getElementById() method.
- Call addEventListener() function on the button with the “click” action and function passed as arguments.
As a result, when the button is clicked, the specified function will be called.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<p>Call Multiple JavaScript Functions on Click of a Button</p>
<button type="button" id="myBtn">Click Me</button>
<p id="msg"></p>
<script>
function displayMessage(){
document.getElementById("msg").innerHTML = "The button has been clicked.";
}
// get reference to button
var btn = document.getElementById("myBtn");
// add event listener for the button, for action "click"
btn.addEventListener("click", displayMessage);
</script>
</body>
</html>
Method 2: Use onclick Attribute
- Add onclick attribute to the button in HTML code.
- Assign the function call to the attribute.
Run the following example, and when the button is clicked, the specified function in the onclick
attribute will be called.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<p>Call Multiple JavaScript Functions on Click of a Button</p>
<button type="button" id="myBtn" onclick="displayMessage()">Click Me</button>
<p id="msg"></p>
<script>
function displayMessage(){
document.getElementById("msg").innerHTML = "The button has been clicked.";
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to call a function when button is clicked.