Last active
December 21, 2015 17:09
-
-
Save jpillora/6338692 to your computer and use it in GitHub Desktop.
Track file clicks with jQuery and Google Analytics (gs.js)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//File Click Tracker (jpillora@think.edu.au) | |
$(document).ready(function() { | |
//show event instead of sending to GA (modifiable) | |
var debug = false; | |
//snippet variables (non-modifiable) | |
var loc = window.location; | |
//watch all form submissions with a 'data-track' attribute | |
$(document).on("click", "a", function(e) { | |
var a = $(this); | |
var category = null; | |
var action = "Click"; | |
var href = a.attr("href"); | |
if(/^mailto\:/i.test(href)) { | |
category = "Mail"; | |
} else if(/\.(pdf|docx?|xlsx?|pptx?)$/i.test(href)) { | |
action += "-" + RegExp.$1; | |
//prefix absolute urls | |
if(/^\//.test(href)) href = loc.protocol + loc.hostname + href; | |
category = "Download"; | |
} else if(/^https?\:\/\//i.test(href)) { | |
category = "External"; | |
} else { | |
return; //do nothing | |
} | |
var track = ["_trackEvent", category, action, href]; | |
if(debug) | |
alert(track.join(', ')); | |
else if(window._gaq) | |
_gaq.push(track); | |
//new tab, so open link now | |
if(a.attr('target') && a.attr('target').toLowerCase() === '_blank') | |
return true; | |
//in half a second - resubmit | |
setTimeout(function() { | |
loc.href = href; | |
}, 500); | |
//prevent the form from submitting | |
e.preventDefault(); | |
return false; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment