Coffescript to track Analytics events
Do you want to track in Google Analytics when a user download a PDF or ZIP file? Just put this script in your code.
timeout = () -> location.href = baseHref + href
$ ->
filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i
baseHref = if $('base').attr('href') != undefined then $('base').attr('href') else ''
$('a').each () ->
href = $(this).attr('href')
if href && href.match(/^https?\:/i) && !href.match(document.domain)
$(this).bind 'click', () ->
extLink = href.replace(/^https?\:\/\//i, '')
_gaq.push ['_trackEvent', 'External', 'Click', extLink]
setTimeout timeout, 200 if $(this).attr('target') != undefined && $(this).attr('target').toLowerCase() != '_blank'
else if href && href.match(/^mailto\:/i)
$(this).bind 'click', () ->
mailLink = href.replace(/^mailto\:/i, '')
_gaq.push ['_trackEvent', 'Email', 'Click', mailLink]
else if (href && href.match(filetypes))
$(this).bind 'click', () ->
extension = if /[.]/.exec(href) then /[^.]+$/.exec(href) else undefined
filePath = href
_gaq.push ['_trackEvent', 'Download', 'Click-' + extension, filePath]
setTimeout timeout, 200 if $(this).attr('target') != undefined && $(this).attr('target').toLowerCase() != '_blank'
This script automates the following:
- Tracks file downloads as events for the following extensions: .zip, .exe, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3
- Tracks outbound clicks as events if the href value contains http:// or https:// and the domain value doesn’t match the current domain.
- Tracks mailto email clicks
Source: Blastam
Written by Carlos Hernández
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Analytics
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#