snippet

How to catch all click on link in Javascript

Here is how to get the click action on each link of your page, if a user clicks on a link, the listener will trigger and enter the function. Adding the preventDefault function tells the browser not to execute the function initially requested, i.e. the click on the link. The user will not be redirected to the requested link, it's up to you to perform the actions you want in the function and redirect the user at the end if needed.

document.addEventListener(`click`, e => {
  if (e.target.tagName.toLowerCase() === 'a') {
    e.preventDefault();
    console.log(`Target link is ${e.target.href}`);
  }
});
Related snippets