Last active
April 4, 2023 18:52
-
-
Save tsvensen/4574206 to your computer and use it in GitHub Desktop.
Abstract+Extend Google Analytics Tracking
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
/** | |
* Google Analytics Tracking | |
* | |
* Abstracting Google Analytics basic _trackEvent and _trackPageview | |
* Easily extended to support specific use cases | |
*/ | |
var TRACK = (function($) { // Yes I know, TRACK is a global variable poluting the global namespace | |
//////////////////////////////////////////////// Example calls (maybe not the best place for them) | |
/** | |
* track events | |
*/ | |
// track clicking of #myElm | |
$('#myElm').click(function() { | |
TRACK.event('My Button', 'my_button_click'); | |
}); | |
// track clicking of #myElm and redirect to google | |
$('#myElm').click(function() { | |
TRACK.event('My Button', 'my_button_click', 'http://google.com'); | |
}); | |
// track page view (use case: 1 page site with multiple "pages") | |
$('#page2').click(function() { | |
TRACK.pageview('demo'); | |
}); | |
//////////////////////////////////////////////// Public Variables and Functions | |
return { | |
/** | |
* event() | |
* | |
* https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide | |
* | |
* Add event tracking | |
* event('Category', 'event_machine_name'); | |
* | |
* Optional URL can be passed to track click then redirect to URL | |
* event('Category', 'event_machine_name', 'http://google.com'); | |
*/ | |
event: function(category, action, url) { | |
// event: function(category, action, label, url) { // track event using label | |
// event: function(category, action, label, val, url) { // track event using label and value | |
var link = url || false; | |
_gaq.push(['_trackEvent', category, action]); // track event | |
// _gaq.push(['_trackEvent', category, action, label]); // track event using label | |
// _gaq.push(['_trackEvent', category, action, label, val]); // track event using label and value | |
// when a link is provided, redirect to the link | |
if (link) { window.location = link; } | |
}, | |
/** | |
* pageview() | |
* | |
* Extend with custom vars | |
* https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables#examples | |
* | |
* Add tracking tag calls to content with: | |
* pageview('home'); | |
* | |
* Add additional params with: | |
* pageview('home','video_id=1&xxx=yyy'); | |
*/ | |
pageview: function(url, tagParams) { | |
var url = url || ''; | |
if (tagParams) { url += tagParams; } | |
_gaq.push(['_trackPageview', url]); | |
} | |
}; | |
}(jQuery)); // closure, pass in jQuery |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment