You are on page 1of 17

(At Least) 10 JavaScript Tricks

Andrew Hood
Managing Director
@lynchpin
3 Opening Thoughts
1. Love it or hate it, JavaScript is still at the core of the majority of
web analytics implementation (failures)
Small fixes/improvements can pay a significant dividend
2. Even if you are not The Developer, understanding some of the
common structures can be a big tactical advantage
Dont assume a web development team has a JavaScript expert
3. There is often a simple way to addressing a specific requirement
But copy and paste from a random website might not be that way
A Few Definitions
Design Patterns (Tricks)
A reusable solution to a commonly occurring problem
JavaScript
Interpreted language: invented by Netscape, destroyed by Microsoft,
elevated by AJAX, now almost standardised by ECMA
jQuery (http://jquery.com)
Free JavaScript library, used on Almost Every Website with some key
benefits for analytics use cases:
(Almost) guaranteed cross browser compatibility
Makes it much easier to scrape and control interaction with in-page elements
A Topical Rant
JavaScript is seriously yet opaquely fussy
Majority of common errors come down to syntax:
myVariable is different to myvariable
false is true
2 > 10
this is not what you think this is
Statements must be terminated;
sometimes // and comments can easily run_into_code();
getElementById might actually do a getElementByName (in IE6 and IE7)
Purists read this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
Pragmatists read this:
http://www.tutorialspoint.com/javascript/javascript_quick_guide.htm
Menu
1. onClick Binding
2. Screen Scraping
3. Outbound Link Tracking
4. URL Manipulation
5. URL Parsing
6. Event Abstraction
7. Form Field Tracking
8. Tracking Video
9. Tracking Scrolling
10. Debugging
Notes and Disclaimers
Unless otherwise specified, all examples use jQuery
Need to include jQuery library on all pages first otherwise
none of this is going to work
No warranty
Use at your own risk, no liability accepted for damage to
your website/home/pets/career/sanity
These slides (will be) available for download here:
http://www.lynchpin.com/measurecamp-september-2013
1. onClick Binding
Scenario
You want to add code to all links or DOM elements of a particular style
Use Cases
Cross-Domain Tracking, Download Tracking, In-Page Event Tracking
// Google Analytics - Cross Domain Tracking Links
$("a[href*='my-other-domain.co.uk']").click(function() {
_gaq.push(['_link', this.href]); return false;
});
// Google Analytics - PDF Download Tracking
$("a[href$='pdf']").click(function() {
_gaq.push(['_trackPageview', this.href]);
});
2. Screen Scraping
Scenario
You want some text that sits in the DOM (Document Object Model) on the page to record in an analytics tool
Use Cases
(Lots of things) but beware coupling with page design!
// Google Analytics Custom Variable from <h1 id="title">Site Section</h1>
var siteSection = $("h1[id='title']").text();
_gaq.push(['_setCustomVar', 1, 'Section', siteSection);
Combined Example (1 & 2)
HTML
<div class="tab_info">
<a id="tab1">Delivery</a>
<a id="tab2">Returns</a>
</div>
jQuery
$("div[class^='tab'] a").click(function() {
var tabName = $(this).text();
void(s.tl(true, 'o', "Tab " + tabName));
});
Breakdown
$("div[class^='tab'] a")// Select all <a> nested within a <div> with a class starting with tab
.click(function() { // Execute the following code whenever a user clicks on those elements
$(this).text() // Grab whatever appears between the <a> </a> tags
s.tl // Track an Omniture SiteCatalyst Adobe Marketing Reports and Analytics event
3. Outbound Link Tracking
Scenario
You want to track exit links (reliably in all browsers)
Use Cases
Exit Links
// Google Analytics Exit Link Tracking
$("a[href^='http']").click(function() {
_gaq.push(['_trackEvent', 'Link Tracking', 'External', this.href]);
setTimeout(function() {
document.location.href = this.href;
}, 100);
return false;
});
4. URL Manipulation
Scenario
You want to modify links within a page
Use Cases
Internal Campaign/Navigation Tracking
// SiteCatalyst Internal Campaign Tracking for <a class="topnav">Menu Item</a> links
$("a.leftbar").each(function () {
this.href = this.href + '#intcmp=topnav';
});
5. URL Parsing
Scenario
You want to extract metadata from the current URL
Use Cases
Content Taxonomy, Query String Parameter Extraction, Fun With Regular Expressions
// SiteCatalyst Extract intcmp URL # parameter from previous example
// Example http://www.mysite.com/blog#intcmp=topnav
s.eVar9=window.location.hash.match(/intcmp=(.*)/)[1];
// Google Analytics Extract Product SKU from URL for Custom Variable
// Example http://www.mysite.com/product/123456789/luxury-kettle-named-for-seo
var productSKU = window.location.match(/product\/([0-9]+)\//)[1];
_gaq.push(['_setCustomVar', 1, 'Product SKU', productSKU);
6. Event Abstraction
Scenario
You want to code in-page event capture into the site and then be flexible with binding to analytics calls
Use Cases
Using Adobe Tag Manager, Not Using A Tag Management System, Simplifying Development
// In-Page Event Trigger (Coded Into Page)
<a href="#" onClick="$('body').trigger({type:'tracking',var1='val1',var2='val2'});">
// Binding to Analytics Tag (Centralised JavaScript File)
$("body").on("tracking", function(event) {
_gaq.push(['_trackEvent', 'Tracking Event', event.var1, event.var2);
});
7. Form Field Tracking
Scenario
You want to fire an event each time a form field is interacted with (withotu interfering with existing validation)
Use Cases
Form Field Tracking
// Google Analytics Form Field Tracking
$(':input').blur(function () {
if($(this).val().length > 0) {
_gaq.push(['_trackEvent', 'Form Field', 'Completed', $(this).attr('name')]);
} else {
_gaq.push(['_trackEvent', 'Form Field', 'Skipped', $(this).attr('name')]);
}
});
8. Tracking Video
Scenario
You want video engagement to fire data into your main analytics tool
Use Cases
Segmentation of Behaviour by Video
Callbacks are your friend too much script for a slide! Try this for starters:
http://www.bluefountainmedia.com/blog/track-youtube-player-events-google-analytics/
function onPlayerStateChange(event) {
if (event.data ==YT.PlayerState.PLAYING) {
_gaq.push(['_trackEvent', 'Videos', 'Play', player.getVideoUrl()]);
}
if (event.data ==YT.PlayerState.ENDED) {
_gaq.push(['_trackEvent', 'Videos', 'Watch to End', player.getVideoUrl()]);
}
}
9. Tracking Scrolling
Scenario
You want to figure out if a user scrolls (to the end of) a page
Use Cases
Long Content, Basic Heatmaps
// Google Analytics Scrolling Detection (50 pixel margin from base of screen)
var bottomOfPageTracked = false;
$(window).scroll(function() {
if (!bottomOfPageTracked) {
if($(window).scrollTop() + $(window).height() > $(document).height() - 50) {
_gaq.push(['_trackEvent', 'Scroll', 'Bottom', location.href]);
}
bottomOfPageTracked = true;
}
});
10. Debugging
Scenario
You want to see whats going on without waiting for GA/SiteCatalyst/WebTrends/ to populate (or not)
Use Cases
Debugging. Defined Test Cases
// Console Logging
$("a[href$='pdf']").click(function() {
console.log("GA Virtual Pageview " + this.href);
_gaq.push(['_trackPageview', this.href]);
});
// CTRL + SHIFT + K in Firefox

You might also like