Robert Scott
Robert Scott

Reputation: 609

Google Tag Manager - Create Event with Inline onclick attribute

I have a website where I am using Google Tag Manager to fire my Google Analytics tracking.

<!-- Google Tag Manager -->
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','********');
</script>
<!-- End Google Tag Manager -->

On the page, I wanted to track link clicks that open a modal window.

So, I put this code:

onclick="ga('send', 'event', 'Test', 'Take-Test', 'English');"

However, that is not working and it's not pushing the event into Analytics.

After doing a lot of digging, I thought maybe the issue is that GTM uses gtag.js instead of the older analytics.js library, so the structure of my onclick event had to be different.

My source for this was: https://developers.google.com/analytics/devguides/collection/gtagjs/migration#track_events

Based on this, I'm thinking my onclick event has to look like this:

onclick="gtag('event', 'Take-Test', {'event_category': 'test','event_label': 'English'});

However, I can't seem to confirm that with a GTM implementation it is using gtag.js, so I don't know if this is correct still.

All I know is that I really want to push this event into Analytics properly.

As a side note, I realize I can probably create GTM firing rules for this, however for reasons beyond my control, I have to create the onclick event in the HTML code and not via GTM.

Many thanks in advance for any insight!

Upvotes: 2

Views: 5354

Answers (3)

nicke-nix
nicke-nix

Reputation: 11

A bit old thread but anyway.

Had the same problem until I put this at the top of page:

<script>window.onload = function(){
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXX-X');
ga('create', 'UA-XXXXXXXX-X'); 
.......

Especially the ga('create', 'UA-XXXXXXXX-X') seems to be crucial.

Upvotes: 1

Raoul Dundas
Raoul Dundas

Reputation: 426

Maybe you should use analytics.js instead of ga.js: https://developers.google.com/analytics/devguides/collection/analyticsjs/events

ga('create', 'UA-IDHERE-X', 'auto');
ga('send', {
  hitType: 'event',
  eventCategory: 'Your Category',
  eventAction: 'Your Action',
  eventLabel: 'Your Label'
});

Upvotes: 0

nyuen
nyuen

Reputation: 8907

Your ga('send' ...) call would not work in this case because

GTM automatically sets unique tracker names for its tags, which will not match the tracker name of your on-page analytics object.

(cf. https://www.lunametrics.com/blog/2015/01/21/gtm-existing-tracking/)

You would either have to find out the tracker name that GTM is using and modify your send call to something like this

ga('trackerName.send', 'event', ...)

or track the click using a GTM tag.

Upvotes: 1

Related Questions