Created
July 24, 2012 12:45
-
-
Save hotzeplotz/3169751 to your computer and use it in GitHub Desktop.
attach Google Analytics event tracking to all PDFs on a page
This file contains hidden or 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
| // jQuery regex filter (http://james.padolsey.com/javascript/regex-selector-for-jquery/) | |
| jQuery.expr[':'].regex = function(elem, index, match) { | |
| var matchParams = match[3].split(','), | |
| validLabels = /^(data|css):/, | |
| attr = { | |
| method: matchParams[0].match(validLabels) ? | |
| matchParams[0].split(':')[0] : 'attr', | |
| property: matchParams.shift().replace(validLabels,'') | |
| }, | |
| regexFlags = 'ig', | |
| regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags); | |
| return regex.test(jQuery(elem)[attr.method](attr.property)); | |
| }; | |
| jQuery(document).ready(function($) { | |
| // track clicks to PDFs hosted in WordPress. | |
| // based on http://www.wduffy.co.uk/blog/tracking-google-goals-with-no-url-using-jquery/. | |
| // uses regex jQuery filter (http://james.padolsey.com/javascript/regex-selector-for-jquery/). | |
| $(':regex(href,(http:\/\/example\.com\/)?\/files\/.*.pdf)').click(function() { | |
| var re = /^(http:\/\/example\.com)?(.*)$/gi; | |
| var originalhref = $(this).attr('href'); | |
| var href = originalhref.replace(re, '$2'); | |
| console.log("PDF download at URI %s tracked with event label '%s'", originalhref, href); | |
| _gaq.push(['_trackEvent', 'PDF', 'download', href]); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment