I currently have Google Analytics added to my webpage and I'm trying to add some events such as files downloaded, buttons clicked, etc.. nothing too complicated. I feel like I must be missing something very obvious, because everything have tried so far has resulted in being able to see the users viewing the website but 0 events showing up on the Google Analytics dashboard. I am entirely self taught and have looked at other questions and answers such as the following:
Google Analytics tracking code doesn't record downloads in RealTime
and
How to track pdf downloads with Google Analytics
I am using the following in my header with the ID# replaced with X's:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXXX-X');
</script>
With the following attempts, with respect to the linked questions:
1st question linked:
<a href="/downloads/Test.pdf" onclick = "gtag('send', 'event', {'event_category': 'download','event_label': 'download_clicked'});">Click here to download a PDF.</a>
2nd question linked:
<script>
var trackDownload = function(url) {
gtag('send', 'event', 'download', 'download_clicked', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
}
</script>
<a href="http://www.mywebsite.com/downloads/Test.pdf" onclick="trackDownload('http://www.mywebsite.com/downloads/Test.pdf'); return false;">Click here to download a PDF.</a>
What am I missing? Any help is very appreciated!
Thanks!
You are mixing syntax of ga
and gtag
.
Syntax to send event with gtag is the following:
gtag('event', <action>, {
'event_category': <category>,
'event_label': <label>,
'value': <value>
});
https://developers.google.com/analytics/devguides/collection/gtagjs/events
So to send your event you have to use this code:
gtag('event', 'download_clicked', { event_category: 'download' });
Where download_clicked is action (category and action are mandatory).