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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.