superdee
superdee

Reputation: 697

How do I get Google Tag Manager to track events?

I am trying track events using Google Tag Manager, here is my code:

<!-- Google Tag Manager -->
(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', 'GTM-MYTAG');

window.dataLayer = window.dataLayer || [];

function gtag() {
    dataLayer.push(arguments);
}

gtag('js', new Date());

gtag('config', 'GTM-MYTAG');

function trackEvent(eventName, eventValue) {
    gtag('event', 'click', {
        'event_category': eventName,
        'event_label': eventValue,
        'value': 1
    });
}

And here is the HTML that fires the event when something is clicked:

<button onclick="trackEvent('Add Button Clicked', 'Header')"
        class="chrome-button chrome-link btn btn-sm btn-sample">
    <div>Add to Chrome - Free</div>
</button>

What am I doing wrong? I have tried going to Google Analytics -> Real Time -> Events and nothing shows up while I click the button. I have also made sure I removed all filters with my IP address. Please let me know if I am missing something.

Upvotes: 0

Views: 1904

Answers (1)

XTOTHEL
XTOTHEL

Reputation: 5198

You've confused GTM and gtag.js. They're two separate libraries for tracking.

Here are the methods you should use to do GA event tracking in GTM: https://support.google.com/tagmanager/answer/6106716?hl=en

If you just want it to work, then replace GTM with:

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

  gtag('config', 'UA-XXXX-1');
</script>

Then have this function trigger as you have:

function trackEvent(eventName, eventValue) {
    gtag('event', 'click', {
        'event_category': eventName,
        'event_label': eventValue,
        'value': 1
    });
}

You'll need nothing else.

Upvotes: 2

Related Questions