1
votes

I am trying to set up Event Tracking through Google Analytics. Getting it to work on text links is easy but I can't seem to get it to work on images. I follow Google's example of how to add the code should be, but it results in an image link that can't be clicked (I click the banner and nothing happens, but I can right click the banner and open in new window and it works).

See below for my code on the link:

<a href="http://keystonetech.com" target="_blank" 
onclick="trackOutboundLink('http://keystonetech.com');return false;"><img 
src="/wp-content/uploads/2017/09/keystone-direct-drive-led-t5.jpg" alt="" 
width="617" height="128" /></a>

And then below is the Google Analytics scripts - 1st one is the standard Universal Analytics GA Script and the bottom one is for tracking the links (again, per the Google link above).

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

  gtag('config', 'UA-437557-32');
</script>
<script>
/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL 
string
* as the event label. Setting the transport method to 'beacon' lets the hit 
be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){document.location = url;}
   });
}
</script>

Any thoughts on where the issue lies would be much appreciated! Thanks much for reading.

1

1 Answers

0
votes

I think I can send you in the right direction. I'm pretty sure the issue is the difference between the various analytics tracking codes. you're using the newest Gtag.js, which appears to have a different event structure than analytics.js

I personally use google tag manager now, but I'm pretty sure the structure to call an event is different for Gtag.js. Here's the page specifically for that:

https://developers.google.com/analytics/devguides/collection/gtagjs/events#recommended-event-parameters

And if I were you, it looks like the actual function would look like:

gtag('event', 'event_name', {
'event_category': categoryName,
'event_label': labelName
});

Which if I'm reading your code right would be basically:

gtag('event', 'click', {
'event_category': 'outbound',
'event_label': url
});

Then be sure you properly trigger that function on the click, and be sure grab the chrome extension google analytics debugger and in the console make sure you see it fire that hit to GA. Tada!