How to Run JavaScript Code When we Click on a Link?

Sometimes, we want to run JavaScript code when we click on a link.

In this article, we’ll look at how to run JavaScript code when we click on a link.

Run JavaScript Code When we Click on a Link

To run JavaScript code when we click on a link, we can attach a click event listener to the a element.

For instance, we can write:

<a href="#">LinkText</a>

to add an a tag.

We set href to # to avoid going to any URL when we click on the link.

Then we write:

const a = document.querySelector('a')
a.addEventListener('click', () => {
  console.log('clicked')
})

to get the a element with document.querySelector.

Then we call addEventListener with 'click' to add a click listener.

The 2nd argument is a callback that runs when we click on the link.

Therefore, we should see 'clicked' logged when we click on the link.

Conclusion

To run JavaScript code when we click on a link, we can attach a click event listener to the a element.