DEV Community

Cover image for Custom Google Analytics events with Javascript.
Stephan Nijman
Stephan Nijman

Posted on • Originally published at since1979.dev

Custom Google Analytics events with Javascript.

Introduction

In this article i would like to show you how you can send custom events to your Google Analytics properties using it's build-in javascript api.

But what is it and why would i care!?

Google Analytics is great for tracking things like page views, but beyond that it is not aware of things like Javascript driven form submissions, Pageviews in Single Page Applications, email and phone link clicks and other conversions/actions taken on your site that don't have a subsequent page view.

Custom events allow us to tell Google Analytics about these events our selfs by using a simple build-in Javascript api that is provided by the tracking snippet you can or already added to your website.

How to send custom events to google analytics

Before we can send custom events we have to make sure that we included the GA Tracking snippet to the head of our website. You can find this tracking code by logging into you Ga Dashboard and then click to Admin (the little cogwheel in the bottem left) > Trackinginfo > Trackingcode and you will find a code snippet like shown below.

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=XX-YOURID-X"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'XX-YOURID-X');
</script>
Enter fullscreen mode Exit fullscreen mode

You can copy this snippet and paste it right before the ending Head tag of your website.

While some WordPress seo plugins allow you to add this snippet via a convenient setting of some sort i have noticed that some of these plugins do not allow us to send custom events. So unless you have a very good reason not to i highly recommend that you add this snippet by hand. Just to prevent some headaches down the road.

Ga vs Gtag tracking codes

There are a couple of different versions of the tracking code snippet floating around. For one there is an older version where the snippet doesn't use the gtag() function but a ga() function instead. While technically we could use the ga() version, just so that we are all on the same page, i would recommend that you update you tracking snippet to the latest version that uses the gtag() function. Ofcourse this is unless you already have some custom code that relies on the older ga() function.

Page view code example

When you are building a Single Page Application your subsequent page views wont register with Analytics because Javascript is handeling the content change instead of the browser.

To fix this we can handle the sending of page views our self. But before we can do that we have to make sure that the tracking snippet we installed isn't sending any. To prevent this we can change the 'config' call inside of the tracking snippet like shown below.

/* Replace this config call */
gtag('config', 'XX-YOURID-X');

/* With this call */
gtag('config', 'XX-YOURID-X', {
  send_page_view: false
});
Enter fullscreen mode Exit fullscreen mode

We can now send our custom page views by calling ussing the code snippet below inside of our router change event handler or from some other place that makes sense for your application.

gtag('event', 'page_view', {
  page_title: 'Page title',
  page_location: location.href,
  page_path: location.pathname
})
Enter fullscreen mode Exit fullscreen mode

You can check if your page views are being registered by google analytics by loging in to your GA dashboard and click to Realtime > Locations.

Form submission code example

Now a days it's more and more common to handle our form submissions with some sort of ajax call. But conversions can't be tracked by analytics by default because there is now "thank you page" we can set up as a goal.

In these cases we can send a custom form_submit event.

const form = document.getElementById('my_form');

form.addEventListener('submit', function(event){

  gtag('event', 'form_submit', {
    event_category: 'Forms',
    event_action: 'Submit',
    event_label: 'Test form' // Name of your form.
  });

  return true;

});
Enter fullscreen mode Exit fullscreen mode

In this snippet we can a reference to our form, and then attach an event listener to it. When the form submits we send a custom event.

You can check if your form submissions are being registered by google analytics by loging in to your GA dashboard and click to Realtime > Events.

Contact link clicks code example

Since email (mailto:) and phone (tel:) links can also not be tracked by analytics. To get these into our dashboard we can send custom link_click events.

const phoneLinks = document.querySelectorAll('a[href^="tel:"]');

phoneLinks.forEach(function(phoneLink){

    phoneLink.addEventListener('click', () => {

        gtag('event', 'link_click', {
            event_category: 'Links',
            event_action: 'Click',
            event_label: 'Phone link'
        });

    }, { once: true });

});
Enter fullscreen mode Exit fullscreen mode

Here we use querySelectorAll to find all phone/tel links. We then loop over these and attach a event listener to each of the links. When any of the links is clicked we send a custom link_click event to our GA dashboard.

We can change this code snippet a bit to handle any email/mailto links like shown below.

const emailLinks = document.querySelectorAll('a[href^="mailto:"]');

emailLinks.forEach(function(emailLink){

    emailLink.addEventListener('click', () => {

        gtag('event', 'link_click', {
            event_category: 'Links',
            event_action: 'Click',
            event_label: 'Email link'
        });

    }, { once: true });

});
Enter fullscreen mode Exit fullscreen mode

Again you can check if your form submissions are being registered by google analytics by loging in to your GA dashboard and click to Realtime > Events.

Contact form 7 submission

I personaly am a big fan of the Contact Form 7 WordPRess plugin to create form. These forms submit by making an Ajax call. If you want you can use the snippet below to track these conversions.

document.addEventListener( 'wpcf7mailsent', function( event ) {

    var form = event.target.querySelector( 'input[name="_wpcf7"]' ).getAttribute("value");

    if( parseInt( form ) == 4839 ) {

        gtag('event', 'form_submit', {
            event_category: 'Forms',
            event_action: 'Submit',
            event_label: 'Test form'
        });

    }

}, false );
Enter fullscreen mode Exit fullscreen mode

In the snippet above we add an event listener to the "wpcf7mailsent" event to listen for CF7 form submissions. When this happends we get the form id from the event. We can then use this id to check which form we are handling and then send an appropriate analytics event.

How to turn events into goals

Within your analytics dashboard you may want to turn your custom events into goals or conversions. This process is different in both versions of analytics. I could explain this all here, but Benjamin Mangold has already made some amazing video's about this. To find out how to do this in the latest GA4 you can check out this video. For the older version of analytics you can check out this video.

Conclusion

As you can see it's relatively easy to implement these custom events, but they can really help you gain much more insights into your users behavior.

Thanks

Subscribe to my Youtube channel.

Follow me on Twitter

Thanks for reading and stay safe

Top comments (1)

Collapse
 
mycodemagic profile image
My Code Magic

WOW so helpful content for better SEO and Analytics 🤓 😎