Boba.js is a small, easily extensible JavaScript library that makes working with Google Analytics easier.
It supports the old
ga.js
library as well as the new
analytics.js
library. It has one out of the box function, trackLinks
,
and makes tracking everything else child's play. Requires
jQuery.
Include your GA script and jQuery, then create a new instance of Boba:
tracker = new Boba
If you're using Browserify:
$ = require("jquery")
Boba = require("boba.js")
Boba.$ = $
tracker = new Boba
All options are optional.
tracker = new Boba({
siteName: 'Mandalore',
pageName: 'Slave I',
defaultCategory: 'category',
defaultAction: 'action',
defaultLabel: 'label',
watch: [
['click', '.js-track-solo', trackSolo],
['click', '.js-track-chewie', trackChewie]
]
})
The name of the site and page, respectively.
You can also get and set tracker.siteName
and tracker.pageName
at any time:
tracker.siteName = 'Mandalore'
tracker.pageName = 'Slave I'
If an event does not have a category, action, or label, these values will be used instead.
You can also change these at any time:
tracker.defaultCategory = 'category'
tracker.defaultAction = 'action'
tracker.defaultLabel = 'label'
An array of arguments to apply to the watch
method on
initialization.
watch: [
['click', '.js-track-solo', trackSolo],
['click', '.js-track-chewie', trackChewie]
]
tracker.watch(eventType, selector, callback)
This will set up delegated event handlers for you. Under the hood, it does something like this:
$('body').on(eventType, selector, function(event) {
tracker.push(callback(event))
})
tracker.watch('click', '.js-track', trackClick)
tracker.watch('change', '.js-track-select', trackSelect)
The callback is passed a
jQuery event object
and should return an object with category
, action
, and label
properties:
{
category: "category",
action: "action",
label: "label"
}
Any values not supplied will use defaults from the options (e.g.
tracker.options.defaultCategory
).
This is a helper that basically does this:
tracker.watch('click', '.js-track', function (event) {
return $(event.currentTarget).data()
})
You can use these data attributes to set the category, action, and label when using this method:
data-ga-category
data-ga-action
data-ga-label
You can pass in an alternate selector if you don't want to use '.js-track'
.
For example, you could use a data attribute instead of a class:
tracker.trackLinks('[data-ga-track]')
This can be used to fire events manually.
tracker.push({
category: "category",
action: "action",
label: "label"
})