Sometimes, we want to call a JavaScript function in a click event handler.
In this article, we’ll look at how to call a JavaScript function in a click event handler.
How to call a JavaScript function in a click event handler?
To call a JavaScript function in a click event handler, we call the function we want in the click handler.
For instance, we write
const f1 = () => {
console.log("f1 called");
};
window.onload = () => {
document.getElementById("save").onclick = () => {
f1();
};
};
to get the element with ID save
with getElementById
.
In it, we set its onclick
property to a function that calls f1
when the element is clicked.
Conclusion
To call a JavaScript function in a click event handler, we call the function we want in the click handler.