I am attempting to use the gaAddons Google Analytics jQuery plugin to track downloads on my site, so any .JPGs, .PNGs, .PDFs etc that have been downloaded I want to track by executing some tracking code.
Clearly something is not working correctly, as I cannot seem to get the _trackEvent
to fire.
This is the JavaScript which resides in the gaAddons plugin.
///////////////////
// _trackDownloads
jQuery(document).ready(function($) {
// helper function - allow regex as jQuery selector
$.expr[':'].regex = function(e, i, m) {
var mP = m[3].split(','),
l = /^(data|css):/,
a = {
method: mP[0].match(l) ? mP[0].split(':')[0] : 'attr',
property: mP.shift().replace(l, '')
},
r = new RegExp(mP.join('').replace(/^\s+|\s+$/g, ''), 'ig');
return r.test($(e)[a.method](a.property));
};
$('a:regex(href,"\\.(zip|mp\\d+|mpe*g|pdf|docx*|pptx*|xlsx*|jpe*g|png|gif|tiff*)")$').live('click', function(e) {
_gaq.push(['_trackEvent', 'download', 'click', this.href.replace(/^.*\/\//, '')]);
});
});
I have the above code included on the page and my simple anchor linking to a PDF file below.
<a href="http://www.ayrshireminis.com/downloads/Files/pdfs/turnberry.pdf" target="blank">DOWNLOAD</a>
Is there something wrong with the JavaScript or is there a simpler way to check for jpg/png/pdf file downloads? I can probably ignore the zip/ppt/tiff files as they will not be on the site.
I have raked around for hours and came across this solution, hope this helps someone:
jQuery(document).ready(function($) {
var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
var baseHref = '';
if (jQuery('base').attr('href') != undefined)
baseHref = jQuery('base').attr('href');
jQuery('a').each(function() {
var href = jQuery(this).attr('href');
if (href && href.match(filetypes)) {
jQuery(this).click(function() {
var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
var filePath = href;
_gaq.push(['_trackEvent', 'Download', 'Click-' + extension, filePath]);
if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
setTimeout(function() { location.href = baseHref + href; }, 200);
return false;
}
});
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.