• Stars
    star
    134
  • Rank 269,990 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Universal analytics event tracking API

trak.js - Universal analytics event tracking API wrapper

Put simply, trak.js is a wrapper for any analytics API. By default it uses Google Universal Analytics but you can override this with the older ga.js or Google Tag Manager if you wish, or you can even add custom event trackers as well, instead of Google Analytics.

npm version Build Status Code Climate
NPM

Getting the Library

Direct downloads

Bower

bower install trak

NPM

npm install trak.js --save

Usage

Include trak.js in your JavaScript bundle or add it to your HTML page like this:

<script type='application/javascript' src='/path/to/trak.js'></script>

or with NPM/Browserify

var trak = require('trak.js');

then run trak.start(); when the DOM is ready (after version 0.3.0 this has changed, run trak(); before version 0.3.0):

// Native JS
document.addEventListener('DOMContentLoaded', function(e) {
  trak.start();
}

// jQuery
$(function(){
  trak.start();
});

API Reference

There are two main ways to use trak.js, in your js code or as data-trak attributes in your markup.

JS implementation:

trak.event({category: '', action: '', label: '' , value: '', nonInteraction: '', eventName: ''})

Fires an analytics event

Arguments object: (these are all optional)

category: A string value of the category value to set
action: A string value of the action value to set
label: A string value of the label value to set
value: An integer
trigger: A string value of a valid event name: click, focus, mouseover etc
nonInteraction: An integer
eventName: A string value used only with Google Tag Manager. Define your GTM event name here

If any property is left undefined, the browser's default value will be used instead.

trak.event({category: 'category value', action: 'action value'});
trak.event({category: 'category value', action: 'action value', label: 'label value'});
trak.event({category: 'category value', action: 'action value', label: 'label value' , value: '', nonInteraction: '', eventName: ''});
Example:
el.addEventListener('click', function() {
  trak.event({category: 'engagement', action: 'signpost', label: 'page.href'});
}
el.addEventListener('mouseover', function() {
  trak.event({
    category: 'engagement',
    action: 'signpost',
    label: 'page.href',
    value: 10,
    nonInteraction: true,
    eventName: 'This is a Google Tag Manager event name'
  });
}

data-trak attr implementation

<a data-trak='{"category":"Rating","action":"Comparison notepad","label":"Up"}' href="#">link</a>

Custom trigger type (new as of v0.4.0)

data-trak attrs can also define a custom trigger type instead of click. Now mouseover, touchstart, focus, blur or any other valid event can be used to trigger a trak event.

<!-- Triggered on focus -->
<a data-trak='{"trigger":"focus","category":"Test category","action":"Test action","label":"Test label"}' href="#pagehref">Custom trigger type</a>

Wildcards

Wildcards can be used to specify certain options like the page title or url.

page.href: Uses window.location.href
<a data-trak='{"category":"Rating","action":"page.href","label":"Up"}' href="#">link</a>
page.title: Uses document.title
<a data-trak='{"category":"Rating","action":"page.title","label":"Up"}'href="#" >link</a>
link.href: Uses this.href
<a data-trak='{"category":"Rating","action":"link.href","label":"Up"}' href="#">link</a>
link.title: Uses this.title
<a data-trak='{"category":"Rating","action":"link.title","label":"Up"}' href="#">link</a>
referrer: Uses document.referrer
<a data-trak='{"category":"Rating","action":"document.referrer","label":"Up"}' href="#">link</a>

Using data-trak attr options with but fire event with js

You can also use data-* attr options but fire events in js. To do this, add the relevant data-trak data and also a data-trakwithjs boolean attribute. This means that the event will only fire when you run it in your js. To run in your js, use the trak.attrEvent method like we have below:

<a data-trakwithjs data-trak='{"category":"Tracked with JS not attr call","action":"link.href","label":"this is a label"}' href="#pagehref">trakwithjs</a>

<script>
  el.addEventListener('click', function() {
    trak.attrEvent.call(this);
  });
</script>

See this in use in the trak demo.


Options

Various default trak.js options can be overridden:

trak.options.clean

Choose whether you'd like to clean the provided category, action and labels

Type: boolean Default: true

trak.options.delimeter

trak.js includes a cleaning method to normalise the arguments that are passed to it. Spaces are converted to an underscore by default but can be overridden by reassigning this value.

Type: string Default: _

trak.options.trackType

Type: string Default: ga

Alternatives:

  • ga : Google Analytics (Universal
  • _gaq : Google Analytics (ga.js) Old version
  • gtm : Google Tag Manager

Use this to change your default tracking provider.

trak.options.additionalTypes

Type: function Default: undefined

Add any other event tracking providers. See below for example:

trak.options.additionalTypes = function(opts) {
  UDM.evq.push(['trackEvent', trak.clean(opts.category), trak.clean(opts.action)]); // trak.clean(opts.label)
  console.log('Fire additional event:', opts);
}

trak.options.debug

Type: boolean Default: false

Show debug logs in the javascript console


Which tracking API's are used?

The default implementation uses latest version of Google Analytics (ga.js) but trak.js also supports the older _gaq type or Google Tag Manager.


Browser Compatibility

trak.js has been tested in the following browsers:

  • Chrome
  • Firefox 3+
  • Opera 10+
  • Internet Explorer 8+

More Repositories

1

design-system-utils

πŸ‘©β€πŸŽ¨ Access your design tokens with ease
TypeScript
537
star
2

gatsby-theme-code-notes

A Gatsby theme for publishing code-related notes to your website
TypeScript
470
star
3

SublimeTextSetupWiki

Enable people to get started with Sublime Text 2 much more quickly
JavaScript
463
star
4

awesome-web-dev-resources

πŸ‘Œ My collection of go-to web development resources
224
star
5

Placeholders

Placeholder HTML & content (lorem ipsum) package for Sublime Text 2
143
star
6

HTML5-Coda-Clips

A selection of HTML5 snippets for use in Panic's Coda web dev app
87
star
7

SimpleSharing

Twitter, Facebook, Google+, Instapaper & LinkedIn social link that do not rely on Javascript
CSS
56
star
8

webpack-recipes

πŸ†˜ A collection of webpack configurations
JavaScript
48
star
9

Otter

Otter is a self-hosted bookmark manager made with Next.js and Supabase with Mastodon integration.
TypeScript
47
star
10

react-design-system-boilerplate

At the moment this project is out-of-date and unmaintained. I hope to revisit it soon though... This is a boilerplate for you to create your own design system in React. It has everything setup to allow you to focus on what it is you care about: creating awesome, reusable components.
TypeScript
46
star
11

SublimeText3UserSettings

My personal Sublime Text 3 User Settings
43
star
12

notes.zander.wtf-gatsby

Notes on code. My memory bank.
TypeScript
40
star
13

Boost

Boost is now Kickoff, see adjacent link
CSS
38
star
14

xkcd-api

πŸ’ͺ CORS enabled version of the XKCD API
JavaScript
37
star
15

stitches-ui

A minimal implementation of Theme UI using Stitches
TypeScript
25
star
16

scriptable-widgets

JavaScript
24
star
17

snippet-generator

⚑ Sublime Text, Atom & VS Code snippet generator
JavaScript
24
star
18

ZM-Resources

List of all scripts & resources I use on a regular basis
23
star
19

Coda-Blackboard-Seestyles

Syntax highlighting themes for Coda
18
star
20

gatsby-starter-code-notes

JavaScript
17
star
21

prismic-reactjs-custom

This is an opinionated fork of prismic-reactjs that allows you to use custom React components instead of standard HTML tags
TypeScript
15
star
22

depdoc

Auto-generate markdown documentation using your package.json's dependencies
JavaScript
13
star
23

Choreographic-Grid

Not ready for prime-time yet, but I hope this could help solve lots of responsive content choreography problems
CSS
13
star
24

pinboard-chrome-extension

This Chrome extension improves the design and UX of Pinboard.in
CSS
12
star
25

zander.wtf-2020

πŸ‘± My personal website
CSS
11
star
26

SublimeText2UserSettings

My personal Sublime Text 2 User Settings
Ruby
11
star
27

SASS-Snippets

A collection of Sublime Text 2 snippets & functions to be used with SASS. Most snippets are to be used specifically with .scss
8
star
28

cloudflare-worker-scraper

Page Metadata Scraper with Cloudflare workers
TypeScript
7
star
29

notes.zander.wtf

TILs, snippetsβ€”my digital code garden 🌱
CSS
7
star
30

cloze-test

Simple Cloze test generator
JavaScript
6
star
31

zander.wtf-2019

πŸ‘± My personal website
JavaScript
6
star
32

Sketch-website-template

Responsive website design template for Sketch 3
6
star
33

pinboard-api

A free, CORS-enabled version of the Pinboard public feeds API
JavaScript
5
star
34

feeds.zander.wtf-svelte

My feeds, built with Svelte, Tailwind, Vite
Svelte
4
star
35

frontmatter-date-setter

JavaScript
4
star
36

alfred-npm-versions

Lookup the latest 15 versions for an npm package
JavaScript
4
star
37

zander.wtf-2017

My old personal portfolio and blog
CSS
4
star
38

programmers-clipboard

πŸ‘Œ Copy unicode characters to your clipboard for use in different programming languages: CSS, Javascript, HTML & plain text
JavaScript
4
star
39

refined-prismic

Browser extension that simplifies the Prismic interface and adds useful features
JavaScript
3
star
40

the-unit

Parses a number and unit string, and returns the unit used
JavaScript
3
star
41

react-npm-package

A base for an npm package that uses React, Vite, Storybook and Vitest
TypeScript
3
star
42

feeds.zander.wtf-nextjs

TypeScript
3
star
43

pinboard-api-cache

A free, CORS-enabled version of the Pinboard public feeds API, but with a one hour cache
JavaScript
3
star
44

rigel-vscode

Port of Rigel theme for VS Code
3
star
45

InteractionCheck.js

Prompt users if they have not interacted with your page for a given amount of time
JavaScript
3
star
46

front-end-vscode-extensionpack

A collection of extensions for working with Front-end Applications in VS Code
3
star
47

fish

My fish shell dotfiles
Shell
2
star
48

scrollObserver

Add class to element when a specific scroll value has been reached
JavaScript
2
star
49

isDateValid

Validate a date
TypeScript
2
star
50

zander.wtf

my site
XSLT
1
star
51

journal

A personal journalling app built with SvelteKit, Supabase & little bit of AI
Svelte
1
star
52

gh-release-experiments

1
star
53

coding-standards

Coding standards and resources
1
star
54

Stacey-Bundle

Textmate bundle for the brilliant Stacey CMS (http://staceyapp.com/)
1
star
55

social-homepage

My social homepage, MrMartineau.co.uk.
CSS
1
star
56

githubwatched

Simple app to show a user's watched & owned repos
JavaScript
1
star
57

zander-react-contentful

JavaScript
1
star
58

issue-templates

1
star
59

HTMLPrototype

My basis for HTML/PHP prototypes
JavaScript
1
star
60

mrmartineau

1
star
61

zander.wtf-after.js

experimental after.js version of my next.js website
JavaScript
1
star
62

gitmoji-alfred-snippets

Gitmoji snippets for Alfred
1
star
63

scripts

Shareable config scripts
JavaScript
1
star
64

grunt-filesizegzip

Grunt plugin to output file size information
JavaScript
1
star
65

raycast-extensions

TypeScript
1
star
66

rollup-routes-test

JavaScript
1
star
67

unsplash-search

Simple Unsplash search
JavaScript
1
star
68

CSSOff2013

My submission for the 2013 CSSOff competition. Unfortunately I was not able to finish due to lack of available time
CSS
1
star
69

rsstojson

Simple API to convert RSS feeds to JSON
TypeScript
1
star
70

KOglossaryLinks

KOglossaryLinks is a jQuery plugin that shows tooltips of glossary terms, from a JSON feed, when hovered (or tapped on touchscreen devices)
CSS
1
star
71

Boost-Snippets

Sublime Text 2 package for my Boost front-end framework
1
star