How to collect link clicks with Simple Analytics

Image of Iron Brands

Published on Nov 23, 2023 and edited on Dec 11, 2023 by Iron Brands

Tracking link clicks are useful when you have an important link that you want to monitor. You wan to see how many visitors click on that link to estimate it's importance.

We'll show the easiest way to capture an event each time a visitor clicks on a specific link on your website.

If you use Google Tag Manager, follow their instructions on setting up a trigger. If you aren't using Google Tag Manager, continue reading.

Let's dive in!

  1. Set up tracking
  2. Gathering relevant data

Set up tracking

We aim to configure an event that will be logged every time a user clicks on this link.

A basic understanding of HTML is required to set up custom events. Prepare an HTML page similar to the one shown below, which includes a variety of tags and an embed script.

link-website.png

Next, we will add a small extra script to the page, considering that the implementation process may vary based on your website's design.

If you are a developer and want to get your hands dirty, feel free to modify it to your liking. If you are the “average-user” just copy/paste it into a script tag on the page where the link is located, as demonstrated in the image below.

The script tag should enclose a paragraph that contains a link to the example website.

link-script-tag.png

This is the script that is needed to collect specific link clicks. You can just copy everything (also the text parts).

<script>
  // We enclose our code in an anonymous function, so it does not interfere with other code
  (function () {
    // What keyword should the links contain to create events for?
    // If the URL is something like https://www.example.com/product/1234
    // keyword = "/product/"
    var keyword = "";

    // Name for the event
    var event = "link_click";

    // This function binds an events to a link
    function bindToLinks(element) {
      // We check if the keyword is filled in
      if (!keyword) return console.warn("Simple Analytics: No keyword set");

      // Filter the links we want to bind to
      if (!element.href || element.href.indexOf(keyword) === -1) return;

      // We use dataset to check if we already added our event to this link
      if (element.dataset.simpleAnalytics) return;
      element.dataset.simpleAnalytics = "link-event";

      // Here we listen for links that are submitted
      element.addEventListener("click", function (event) {
        // Stop when we already handled this event
        if (element.dataset.simpleAnalyticsClicked) return;

        // If the Simple Analytics script is not loaded, we don't do anything
        if (!window.sa_loaded) return;

        // We prevent the visitor from being navigated away, because we do this later after sa_event
        event.preventDefault();

        // We look for a button in the link to find the button text
        var text = element.textContent ? element.textContent.trim().toLowerCase() : null;

        // We add this text to the metadata of our event
        var metadata = {
          text: text,
          hostname: element.hostname,
          path: element.pathname,
          id: element.getAttribute("id"),
          classes: element.getAttribute("class")
        };

        // We send the event to Simple Analytics
        window.sa_event(event, metadata, function () {
          // Now we click the link for real
          element.dataset.simpleAnalyticsClicked = "true";
          element.click();
        });
      });
    }

    // This function finds all links and passes it to the bindToLinks function
    function onDOMContentLoaded() {
      document.querySelectorAll("a").forEach(bindToLinks);
    }

    // This code runs the onDOMContentLoaded function when the page is done loading
    if (document.readyState === "ready" || document.readyState === "complete") {
      onDOMContentLoaded();
    } else {
      document.addEventListener("readystatechange", function (event) {
        if (event.target.readyState === "complete") onDOMContentLoaded();
      });
    }

    // If there is no MutationObserver, we skip the following logic
    if (!window.MutationObserver)
      return console.warn("Simple Analytics: MutationObserver not found");

    // We look for new link elements when the MutationObserver detects a change
    var callback = function (mutationList) {
      mutationList.forEach(function (mutation) {
        mutation.addedNodes.forEach(function (node) {
          // We look for link elements in the page
          if (node && node.tagName === "A") bindToLinks(node);
        });
      });
    };

    // This is the observer that detects changes on the page
    // it can happen that new links are created after the inital page load
    // For example, in a modal that pops up to change some data.
    var observer = new MutationObserver(callback);

    // Here we start observing the page for changes
    observer.observe(document.body, { childList: true, subtree: true });
  })();
</script>

Gathering relevant data

The provided code will resemble the following: It begins with a function and then specifies a keyword and an event name.

The rest of the script functions are not crucial; you do not need to modify them unless you are a developer with experience in making such adjustments. You only need to alter the “keyword name” and “the event name”.

Choose a “keyword name” that is part of the URL of the link. For example, if the website says something like "duckduckgo.com/blog/how-to-be-private”, you can modify the keyword to "duckduckgo" or "blog" to capture all URLs with "blog" in the URL.

For now, we will keep it simple and use "example" as the keyword. The “event name” will be displayed in your dashboard in the Events Explorer. In this case, it is called "Link_Click," but you can change it to any name you prefer.

Upon examining the code, you will notice it sends data such as text, hostname, path, ID, and classes. You can remove or add information if desired; otherwise, no changes are necessary.

Once the script is set up, save the page, deploy it to your website, and refresh. Your newly-created event should now be trackable.

So if we click on the “example.com” link to test it and we navigate to our Events Explorer dashboard, we should see a new event, displayed as "Link_Click." You can filter it by the link and add metadata fields, such as path, hostname, and classes using the “add column” dropdown.

link-click.png

To set up events for multiple links, simply repeat the process of copying and pasting the script and updating the event name and keyword parameters. This is how you can successfully configure event tracking for specific links on your website.

If you want to collect all outbound link clicks, you can also set-up our automated events script.