Reputation: 19
I am attempting to use Event tracking in Google Analytics. In order to achieve this I need to add an onclick attribute to certain links (The ones I was asked to track) like so:
<a href="http://www.example.com" onclick="trackOutboundLink('http://www.example.com'); return false;">Check out example.com</a>
The CMS I am using does not have an option to add onclick events to the menu and I don't want to track every link in the main navigation. I only have a beginner's level understanding of javascript, but I have been looking for a way to use it to insert the onclick status above to only certain href values.
Any assistance would be greatly appreciated.
Upvotes: 0
Views: 278
Reputation: 405
There seems nothing wrong in your syntax, its probably the quotes that are causing the problem.
<a href="http://www.example.com" onclick=" trackOutboundLink('http://www.example.com'); return false; ">Check out example.com</a>
Upvotes: 0
Reputation: 346
Alternatively, if you would like to use your existing trackOutboundLink function, this would attach a click event to all outboud links going to http://www.example.com:
$(function() {
// adding onclick event to this particular link
$('a[href="http://www.example.com"]').click(function(event) {
// preventing the user from navigating away from the page, temporarily
event.preventDefault();
// GA tracking
trackOutboundLink('http://www.example.com');
// continue default behavior for the click
window.location = 'http://www.example.com';
}); // end click event
}); // end document ready
You may want to consider redirecting the user using the callback hitCallback:
ga('send', {
'hitType': 'event',
'eventCategory': '...',
'eventAction': '...',
'eventLabel': '...',
'hitCallback': function(){
// redirect:
window.location = 'http://www.example.com';
}
}
Upvotes: 1
Reputation: 8907
You can embed the GA send method into the onclick:
onclick="ga('send','event','outbound','click','http://www.example.com');"
This would likely do what the trackOutboundLink function does (assuming you were basing your example from this https://support.google.com/analytics/answer/1136920?hl=en).
Upvotes: 0