How to track click events with google analytics

emersonthis picture emersonthis · Apr 15, 2014 · Viewed 13.1k times · Source

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?

Answer

Blexy picture Blexy · Apr 15, 2014

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');
});