Reputation: 455
So I'm trying to implement some event tracking in Google Analytics. I'm trying to use jQuery selectors to determine when a user clicks a link in my navigation and then create a custom variable that gets pushed to Google Analytics. I can't seem to get it to work -- any ideas?
$(function () {
$('ul.ga-nav li a').click(function () {
var element = jQuery(this).attr("id");
if (element == 'menu-item-27561') {
element = 'nav-home';
}
else if (element == 'menu-item-31997') {
element = 'nav-buickgmc';
}
else if (element == 'menu-item-28165') {
element = 'nav-used';
}
else if (element == 'menu-item-27560') {
element = 'nav-service';
}
else if (element == 'menu-item-30679') {
element = 'nav-used';
}
else if (element == 'menu-item-30650') {
element = 'nav-finance';
}
else if (element == 'menu-item-29954') {
element = 'nav-contact';
}
_gaq.push(['track_Event', 'Site Usage', 'Navigation', element]);
});
});
Upvotes: 0
Views: 722
Reputation: 2561
This could be because the navigation to the next page is happening before the google code completes and so that code gets cancelled. You could cancel the default action of the link and let javascript handle the navigation to the next page from within the _gaq queue
so the end of your click function would look like this:
$('ul.ga-nav li a').click(function () {
//....your code
var that = this;
_gaq.push(['_trackEvent', 'Site Usage', 'Navigation', element]);
_gaq.push(function () {
location = $(that).attr('href');
});
return false;
});
Upvotes: 0
Reputation: 137350
I am not sure whether it will fix your problem, but for sure you can simplify your code to look like this:
$(function(){
$('ul.ga-nav li a').click(function(){
var element = jQuery(this).attr("id");
var elements = {
'menu-item-27561': 'nav-home',
'menu-item-31997': 'nav-buickgmc',
'menu-item-28165': 'nav-used',
'menu-item-27560': 'nav-service',
'menu-item-30679': 'nav-used',
'menu-item-30650': 'nav-finance',
'menu-item-29954': 'nav-contact'
};
if (element in elements) {
element = elements[element];
};
_gaq.push(['_trackEvent', 'Site Usage', 'Navigation', element]);
});
});
Did it help?
Upvotes: 0
Reputation: 4730
I think this is just a semantic error, you have:
_gaq.push(['track_Event'....]);
when it should be:
_gaq.push(['_trackEvent'....]);
notice the underscore
Upvotes: 2