Sometimes you run into a situation when building a website where you want to catch all the link clicks within your website. This can easily be done with JavaScript.

How to catch all link clicks with JavaScript

Sometimes you run into a situation when building a website where you want to catch all the link clicks within your website. This can easily be done with JavaScript.

Catching click events inside your website document is one of the most useful skills to master when doing web development.

When you are building your website, most likely your users are going to be interacting with the user interface.

When users click on the elements on your website, you want to be able to program your website to do different things when the user clicks on different elements.

With this example code below, you’ll be able to catch all the clicks on every anchor-element on your website.

document.addEventListener(`click`, e => {
  const origin = e.target.closest(`a`);
  
  if (origin) {
    const href = origin.href;
    console.log(href);
  }
});

This can be useful in situations where you want to send custom events to your APIs, such as Google Analytics events when a link is clicked.

If you were to send a Google Analytics event with this JavaScript code, it would have to be modified a little, like this:

document.addEventListener(`click`, e => {
  const origin = e.target.closest(`a`);
  
  if (origin) {
    const href = origin.href;
    ga('send', 'event', {
      eventCategory: 'Links',
      eventAction: 'click',
      eventLabel: href
    });
  }
});

As you can see, the code changed from line 6, where we added a new function call that uses Google Analytics API to send a custom event.

Programming

Related contents

  1. Why Using WordPress Might Be Harmful To Your Online Business
  2. Skills And Technologies Every Senior Software Developer Needs To Learn
  3. Building sustainable websites with renewable energy
  4. Introduction to Static Websites: What, When, and How?
  5. 31 Page Speed Hacks to Make Your Website Lightning Fast