Created
August 17, 2012 12:02
-
-
Save dommmel/3378328 to your computer and use it in GitHub Desktop.
Track clicks with Google Analytics and Mixpanel
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
# Track clicks with Google Analytics and Mixpanel | |
# | |
# == How to use == | |
# Links that have the "data-track_event" attribute set will be tracked when clicked. | |
# | |
# == How it works == | |
# The to-be-tracked events are stored in a cookie and sends to the Google Analytics and Mixpanel | |
# with the next page requests. | |
# | |
# | |
# == Format of the "data-track_event" attribute == | |
# | |
# data-track_event='["EventName",{"mp": {attr1:"test", attr2: 2}, ga: ["noch", "und noecher"]}]'' | |
# minimum data is data-track_event="EventName" | |
# | |
# if additionaly the attribute "data-track_event_now" is set to true (default=false) the event will be tracked right away | |
# instead of with the next page request, this is useful e.g. for ajax events that don't lead to a page relaod | |
# | |
# Caution: Use single ticks (') to surround the json string as the css attribute and (") inside the string | |
$(document).ready -> | |
tracking_cookie_name = "click_tracking_queue" | |
data_attr = "track_event" | |
data_now_attr = "track_event_now" | |
css_attr = "data-#{data_attr}" | |
css_now_attr = "data-#{data_now_attr}" | |
# Parse data stored in cookie and send events to Google Analytics and Mixpanel | |
track_event = (data) -> | |
# Extract event name | |
unless (data instanceof Array) | |
eventName = data | |
else | |
eventName = data[0].trim() | |
gaPushData = ['_trackEvent', eventName] | |
# check for optional parameters | |
if (data.length > 1) && (data instanceof Array) | |
# Extract mixpanel paramters | |
if data[1]["mp"]? | |
mixpanel.track(eventName, data[1]["mp"]) | |
else | |
mixpanel.track(eventName) | |
if data[1]["ga"]? | |
gaPushData=gaPushData.concat(data[1]["ga"]) | |
_gaq.push(gaPushData) | |
# no optinal parameters given | |
else | |
_gaq.push(gaPushData) | |
mixpanel.track(eventName) | |
# Bind click events | |
$(document).on "click",'[' + css_attr + ']', -> | |
data = $(this).data(data_attr) | |
serial_data = JSON.stringify data | |
if $(this).data(data_now_attr) | |
track_event(data) | |
if $(this).attr("target") is "_blank" | |
that = this | |
setTimeout (-> | |
location.href = that.href | |
), 400 | |
return false | |
else | |
$.cookie(tracking_cookie_name, serial_data) | |
# Send events stored in the cookie | |
event = $.cookie(tracking_cookie_name) | |
if (event) | |
$.cookie(tracking_cookie_name,null) | |
jsonData= JSON.parse(event) | |
track_event(jsonData) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment