Shoora
1/14/2014 - 10:20 PM

Track downloads with Google Analytics & BU GA tracker

Track downloads with Google Analytics & BU GA tracker

(function ($) {
	var filter_from_url = window.location.protocol + "//" + window.location.host,
        tracked_types_formatted = '',
        trackedTypes = ['pdf'];
 	
	trackedTypes.forEach(function(t){
		tracked_types_formatted = tracked_types_formatted + "a[href$='."+t+"'],";
	});
 
	tracked_types_formatted = tracked_types_formatted.slice(0,-1);
 
 	function trackDownload(link, filetype, filename, target) {
		var args,
			currentPath = location.pathname.split('/');

		try {
			args = {
				category: "file downloaded - /" + currentPath[1],
				action: filetype,
				label: filename
			};
			bu_ga_track_event(args);

			if( "_blank" == target ){
				window.open( link );
			} else {
				setTimeout(function(){
					window.top.location.href = link;
				}, 150);
			}

		} catch (err) {}
		return;
	}
	
	function bu_ga_track_event(args) {
		if (typeof args.value === 'undefined' || typeof args.value === 'null' || isNaN(args.value)) {
			args.value = 0;
		}
	
		if (typeof args.delay === 'undefined' || typeof args.delay === 'null') {
			args.delay = 0;
		}
	
		if (typeof args.noninteract === 'undefined' || typeof args.noninteract === 'null') {
			args.noninteract = true;
		}
	
		args.value = parseFloat(args.value);
		var i, trNames = bu_ga_get_trackers();
	
		_gaq.push(['_trackEvent', args.category, args.action, args.label, args.value, args.noninteract]);
	
		for (i = 0; i < trNames.length; i++) {
			_gaq.push([trNames[i] + '._trackEvent', args.category, args.action, args.label, args.value, args.noninteract]);
		}
	
		if (args.delay) {
			setTimeout(function() {
				return true;
			}, 100);
		}
	}
 
	$(document).on("click", tracked_types_formatted, function (e) {
		var filetype = this.href.split('.').pop(),
		path = this.href.replace(window.location.protocol + "//" + window.location.host,"");
	
	        e.preventDefault();
	
	        trackDownload(this.href, filetype, path, this.target);
	});

}(jQuery));