0

I'm trying to send an analytics event on a button click and it's not working. When I look in Analytics reports in Realtime > Events section, I can see one active user (the site isn't public yet, so I'm the only user) but I see no events for active users and no events in the last 30 min. In the Events per minute graph I have a flat line also. Active users and page views work just fine.

I have this JS in my page header:

 <#-- Global site tag (gtag.js) - Google Analytics -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-1"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'UA-XXXXXXXXX-1');
  </script>

and this event on the button:

onclick="javascript:ga('send', 'event', 'buttons', 'click', 'Test 123');"

and it doesn't work.

Even if I call the ga function from the JS console, there is no event recorded. The function returns undefined and nothing goes on the network. The ga function doesn't seem to be doing anything. No errors either.

What am I doing wrong?

1 Answer 1

3

The GA tracking code snippet example is Global Site Tag gtag.js version of GA, however the event tracking code format in your example is Universal analytics.js format and also should not need javascript: in it.

Instead try the following:

onclick="gtag('event', 'click', {'event_category': ''buttons, 'event_label': 'Test 123'});"  

Depending on what sort of onclick it is that you are trying to track, if you modify the tracking code to use https transport and mechanism, beacon instead of the default of image, it should help negate the need of callbacks if the click for example results in a new page being loaded or some similar action which may occur before GA is able to track the onclick event. eg

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

  gtag('config', 'GA_MEASUREMENT_ID', { 'transport_type': 'beacon'});
</script>

https://developers.google.com/analytics/devguides/collection/gtagjs/sending-data#specify_different_transport_mechanisms

1
  • Well, that makes perfect sense :D. It works now. Thank you!
    – Kijit
    Commented Jul 2, 2020 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.