How to Track JavaScript and Ajax Events with Google Analytics

Share this article

Tracking events with Google Analytics

Key Takeaways

  • Google Analytics can be used to track JavaScript and Ajax events on a website, providing valuable insights into user behavior. This involves embedding the analytics tracking code into every webpage and using the ‘ga’ command to send an event when a specific JavaScript AJAX event occurs.
  • In-page events such as Ajax calls, video plays, document downloads, social media interactions, client-side interactions, and outbound links can be recorded using JavaScript code. Parameters such as event category, event action, event label, and event value can be used to describe the event for analytics.
  • Social media interactions can be tracked using Google’s Social Interaction API, which requires parameters like the social network, the type of action, and the target of the social interaction. Tracked events can be viewed in Google Analytics under the ‘Behavior’ section.

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.

Frequently Asked Questions (FAQs) on Google Analytics and JavaScript AJAX Events

How Can I Set Up Google Analytics to Track JavaScript AJAX Events?

Setting up Google Analytics to track JavaScript AJAX events involves a few steps. First, you need to have Google Analytics installed on your website. Once installed, you can use the ‘ga’ command to send an event when a particular JavaScript AJAX event occurs. The ‘ga’ command requires three parameters: the category, action, and label of the event. The category and action are required, while the label is optional. You can use these parameters to describe the event in a way that makes sense for your analytics.

What Are Some Common JavaScript AJAX Events That Can Be Tracked?

There are numerous JavaScript AJAX events that can be tracked using Google Analytics. Some of the most common ones include clicks, form submissions, page loads, and AJAX updates. By tracking these events, you can gain a better understanding of how users interact with your website and use this information to improve the user experience.

How Can I View the Tracked Events in Google Analytics?

Once you’ve set up event tracking, you can view the tracked events in Google Analytics by navigating to the ‘Behavior’ section and then clicking on ‘Events’. Here, you’ll see a breakdown of all the events that have been tracked, categorized by the parameters you set when sending the ‘ga’ command.

Can I Track Multiple AJAX Events at Once?

Yes, you can track multiple AJAX events at once. Each event you want to track will require its own ‘ga’ command with the appropriate parameters. This allows you to track a wide range of events and gain a comprehensive understanding of how users interact with your website.

How Can I Use the Tracked Event Data to Improve My Website?

The data you gather from tracking AJAX events can provide valuable insights into user behavior. For example, if you notice that users often click on a particular button but rarely complete the form that follows, you might decide to make changes to the form to make it more user-friendly. By analyzing the event data, you can identify areas of your website that could benefit from improvement.

What If I’m Not Seeing Any Data in Google Analytics?

If you’re not seeing any data in Google Analytics, there could be a few reasons for this. First, make sure that you’ve correctly installed Google Analytics on your website and that you’re sending the ‘ga’ command correctly. If everything seems to be set up correctly but you’re still not seeing data, it could be that there’s a delay in the data appearing in Google Analytics. It can take up to 24 hours for data to appear.

Can I Track AJAX Events on a Single Page Application?

Yes, you can track AJAX events on a single page application. In fact, tracking AJAX events can be particularly useful for single page applications, as these types of applications often rely heavily on AJAX.

How Can I Test That My Event Tracking Is Working Correctly?

You can test that your event tracking is working correctly by triggering the event you’re tracking and then checking in Google Analytics to see if the event has been recorded. Remember, it can take up to 24 hours for data to appear in Google Analytics.

Can I Use Google Analytics to Track Events on Mobile Devices?

Yes, Google Analytics can be used to track events on mobile devices. The process for setting up event tracking is the same, regardless of the device that the user is using.

What Are Some Best Practices for Tracking AJAX Events?

Some best practices for tracking AJAX events include using descriptive categories, actions, and labels for your events, testing your event tracking to ensure it’s working correctly, and regularly reviewing your event data to gain insights into user behavior.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

ajaxanalyticsanalytics-hubgoogle analyticsGoogle Tutorials & Articlesjavascriptlearn-ux-analyticsstatistics
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week