Categories
JavaScript Answers

How to call a JavaScript function in a click event handler?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *