How to track click events with google analytics
Asked Answered
T

1

9

I'm trying to record events when users click specific elements, but no events are being recorded. Here's my code:

/* JQUERY PREPENDED ALREADY... */

/* STANDARD GOOGLE ANALYTICS CODE */
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-12345678-1', 'mysite.com');
ga('send', 'pageview');

var _gaq = _gaq || [];

/* MY EVENT TRACKING CODE (NOT WORKING) */
$(".logo-btn-js").click( function() {
        _gaq.push(['_trackEvent', 'Clicks', 'Logo', 'User clicked the "logo" on first screen']);
    }
);
$(".websites-btn-js").click( function() {
        _gaq.push(['_trackEvent', 'Clicks', 'Websites', 'User clicked the "websites" btn']);
    }
);
...

What am I doing wrong?

Terricolous answered 14/4, 2014 at 22:28 Comment(1)
use google tag managerEdva
G
18

You're using Universal Analytics (analytics.js):

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-12345678-1', 'mysite.com');
ga('send', 'pageview');

With Classic Analytics (ga.js) event syntax (which won't work):

_gaq.push(['_trackEvent', 'Clicks', 'Logo', 'User clicked the "logo" on first screen']);

To fix, use Universal Analytics event syntax:

$(".logo-btn-js").click( function() {
        ga('send', 'event', 'Clicks', 'Logo', 'First Screen');
});
Gravamen answered 14/4, 2014 at 23:23 Comment(1)
From google analytics specs: "Tracking outbound links and forms can be tricky because most browsers will stop executing JavaScript on the current page once a new page starts to load. One solution to this problem is to set the transport field to beacon" But caniuse.com says beacon api not supported in IE and Safari. So you would need to wait for ga send to complete before loading the target page.Elle

© 2022 - 2025 — McMap. All rights reserved.