Skip to content

Instantly share code, notes, and snippets.

@grayghostvisuals
Last active December 18, 2015 13:59
Show Gist options
  • Save grayghostvisuals/5793425 to your computer and use it in GitHub Desktop.
Save grayghostvisuals/5793425 to your computer and use it in GitHub Desktop.
Google Analytics Event Tracking for Open Source File Downloads. Example depicts the better way of including this event tracking script from an external file over inline event handlers suggested by the Google Analytics Event Tracking documentation.
// Example Markup For Download Link
//
// data-name is the name of your project's package download file
// data-category is the name for your tracking event. i.e. (“Download” or “Video” or simply “Click” if you must)
// <a href="#" class="dl-item" data-pkgcategory="" data-pkgname="">Download Our File</a>
//
// For Example:
// <a href="//myproject.com/download-sass.scss" class="dl-item" data-pkgcategory="Downloads" data-pkgname="Sass Port">Download Sass File</a>
// Include this script just before the </body> of your document.
// This is the script suggested for event tracking per the analytics documentation.
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'XX-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
// ==========================================================================
// Google Analytics Event Tracking
// Tracks when a user clicks any of our port download buttons
// Use this script in an external JS file of your choice.For example “main.js”
$('.dl-item').on('click', function() {
var projectUrl = $(this).attr('href'), // project's package/file download URI
category = $(this).data('pkgcategory'), // category for your tracking event.
action = '', // project description action. i.e.(My Project File Download)
packageName = $(this).data('pkgname'), // name of the package/file users will download. i.e. (Sass Port or Script or CSS)
pushTrackEvent = function() {
_gaq.push(['_trackEvent', category, action, projectUrl, packageName]); // the call to push tracking event data to your analytics.
};
// Push Track Event Data Function
// https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide#SettingUpEventTracking
pushTrackEvent();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment