Categories
JavaScript Answers

How to add onclick event programmatically with JavaScript?

Spread the love

Sometimes, we want to add onclick event programmatically with JavaScript.

In this article, we’ll look at how to add onclick event programmatically with JavaScript.

How to add onclick event programmatically with JavaScript?

To add onclick event programmatically with JavaScript, we can set the onclick property of an element.

For instance, we write:

<button>
  click me
</button>

to add a button.

Then we write:

const button = document.querySelector('button')
button.onclick = () => {
  console.log('clicked')
}

to select the button with querySelector.

Then we set the button.onclick property to a function that logs 'clicked'.

As a result, we see 'clicked' logged when the button is clicked.

Conclusion

To add onclick event programmatically with JavaScript, we can set the onclick property of an element.

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 *