🤯 50% Off! 700+ courses, assessments, and books

How to Track JavaScript and Ajax Events with Google Analytics

Craig Buckler
Share

Hands up all those using Google Analytics to track users on your website. To be fair, it’s probably quicker to count those who don’t use Google Analytics. Whatever your opinion of Google and its plans for world domination, Google Analytics is an amazing tool that has revolutionized web statistics.

In order to view visitor reports, you’ll need to embed the analytics tracking code into every web page on your website.

Here’s how:

  1. Sign-up for Google Analytics (or associate your existing Google/Gmail ID).
  2. Open the Admin section (cog icon) on the left-hand side and Create new account from the ACCOUNT column.
  3. Open the PROPERTY column and click Create new property using your website’s URL. Your website will then be assigned a tracking ID which has the format UA-XXXXX-Y.
  4. Open Tracking Code from the Tracking Info sub-menu.

While there are several older variations of this tracking code around, Google recommends the following JavaScript implementation for modern browsers:

<!-- Google Analytics tracking code -->
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<!-- end Google Analytics tracking code -->

Add this to your website’s template and replace UA-XXXXX-Y with your new tracking ID. Google suggests inserting the tracking code in the <head> section of your HTML, but essentially it can go anywhere. I like to insert it at the bottom of the page (before the closing body tag) or call it after the page has loaded to ensure it has a lesser priority than other tasks (this is better for website performance).

From this moment onwards, Google Analytics will track and report on your users’ visits, as well us their user demographics and user behavior and across your website.

In-page Events

The standard tracking code mentioned above is adequate for simpler, content-only websites and basic WordPress themes, but it doesn’t record “in-page” events such as:

  • Ajax calls
  • video plays
  • document downloads
  • social media interactions
  • client-side interactions
  • outbound links, or…
  • any other activity that doesn’t incur a normal page load.

In-page events can be recorded with the following JavaScript code, which calls the global Google Analytics object:

ga(
  'send',
  'event',
  [eventCategory],
  [eventAction],
  [eventLabel],
  [eventValue]
);

An alternative is to use a JavaScript object:

ga('send', {
  hitType: 'event',
  eventCategory: [eventCategory],
  eventAction: [eventAction],
  eventLabel: [eventLabel],
  eventValue: [eventValue],
  [transport: beacon ]
});

Let’s look at each of the lines in this object individually …

[eventCategory] (required)

A single name for events of a specific type (for example, “video” for a video interaction or “download” for a PDF link).

[eventAction] (required)

A user interaction that results in the event being fired (for example, “play” for video or the filename for a download).

[eventLabel] (optional)

An optional label for categorizing events. For example, we could use a campaign name such as “Winter Campaign”. All events, whether they are downloads, video plays, outbound links, or otherwise, can be categorized using the same label.

[eventValue] (optional)

An optional numerical value associated with the event. For a video, we might define the filesize or the length of the video so that total and average bandwidth statistics can be reported.

You could also record a monetary amount, but be aware that Google Analytics has special facilities for recording ecommerce transactions.

[transport: beacon] (optional)

This is used to track forms and outbound links. Browsers stop executing JavaScript on the current web page when a new page starts to load, so this option doesn’t expect a response.

Simple Link Tracking

Event tracking can be used to record something like a PDF download using an inline onclick event:

<a href="document.pdf" onclick="ga('send', 'event', 'download', this.href); return true;">download</a>

In this example, eventCategory is set to download and eventAction is the file URL.

More efficiently, we could define a single JavaScript event handler to record all PDF downloads no matter how many are:

// record all PDF download events
document.body.addEventListener('click', e => {
  let t = e.target;
  if (t.href && t.href.endsWith('.pdf')) {
    ga('send', {
      hitType: 'event',
      eventCategory: 'download',
      eventAction: t.href,
      transport: beacon
    });
  }
}, false);

Social Media Interaction

Event tracking can also be used to track social media interactions on your website. Google offers a Social Interaction API for this, which is a spin-off of the event tracking snippet:

ga(
  'send',
  'social',
  [socialNetwork],
  [socialAction],
  [socialTarget]
);

You could also use this:

ga('send', {
  hitType: 'social',
  socialNetwork: [socialNetwork],
  socialAction: [socialAction],
  socialTarget: [socialTarget]
});

Again, let’s look at each of the lines in this object individually …

[socialNetwork] (required)

The related social network (e.g. Facebook, Twitter, …).

[socialAction] (required)

The type of action (e.g. like, send, tweet, …).

[socialTarget] (required)

The target of the social interaction. This is typically a URL.

Event Tracking in Real-Time Reports

Event actions should be available immediately in the real-time reports (Real-Time → Events). More detailed information is available after 24 hours in the Behavior → Events section.

For more information, refer to the Google Analytics documentation:

Make sure to check out more articles in our UX Analytics series.