Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@chrisbuttery
Last active May 3, 2019 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisbuttery/10334697 to your computer and use it in GitHub Desktop.
Save chrisbuttery/10334697 to your computer and use it in GitHub Desktop.
Track GA Events

track-event

Delegate a listener for the blur() event, on document.

This component is predominantly used to record 'blur' events on form elements. However is flexible enough to be customised.

Installation

$ component install nib-components/track-event

.trackEvent(category, [el, type, capture]);

The default action is to add an event listener on window.document for the 'blur' event.

On blur(), send the event category and properties to ga.

If the element that has experienced the 'blur' event, we send:

gaq('send', 'event', category, 'blur', 'skipped', elementName);

otherwise, if its populated, send:

gaq('send', 'event', category, 'blur', 'completed', elementName);

Example

//default use case

require('track-event')('contact-form');

// optional

var trackEvent = require('track-event');
var form = document.querySelector('.contact-form');
trackEvent('contact-form', form, 'click', false);
// 'click' events are scoped to the form element instead of body.

API

category (required)

The category you wish to record the event for.

require('track-event')('contact-form');

This will record the event under 'contact-form'.

Default: 'document'

element (optional)

The element you wish to delegate the event from.

Default: window.document

type (optional)

The event type. e.g. 'click'.

Default: 'blur'

capture (optional)

The event capture for the event listener.

Focus and blur events don’t bubble. But they should be captured from the window on downward.

Default: true

License

MIT

{
"name": "track-event",
"version": "0.0.1",
"scripts": [
"index.js"
],
"main": "index.js",
"dependencies": {
"nib-components/analytics": "0.0.2"
}
}
var gaq = require('analytics');
module.exports = function(category, el, type, capture){
var evtCat = category || 'document';
var evtEl = el || document;
var evtType = type || 'blur';
var evtCapture = capture || true;
function handler(el){
// IE hack - ensure el.srcElement.name isnt undefined
if (el.srcElement.name != null){
if (!el.srcElement.value){
gaq('send', 'event', evtCat, evtType, 'skipped', el.srcElement.name);
}
else {
gaq('send', 'event', evtCat, evtType, 'completed', el.srcElement.name);
}
}
}
// stupid IE first
if (evtEl.attachEvent) {
evtEl.attachEvent('onfocusout', handler);
}
else if (evtEl.addEventListener) {
evtEl.addEventListener(evtType, handler, evtCapture);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment