Google Analytics Events Example
// Upon document ready, have jQuery do the following
$( function(){
var gaJsHost = ( ( "https:" === document.location.protocol ) ? "https://ssl." : "http://www." );
// use jQuery to call the Google Analytics JavaScript
$.getScript( gaJsHost + "google-analytics.com/ga.js", function(){
// tell Analytics about the current page load using standard _trackPageview method
try {
var pageTracker = _gat._getTracker( $.mcm.apiKeys.analytics );
// the standard page tracking code
pageTracker._trackPageview();
// we're also interested in capturing the page load dime
pageTracker._trackPageLoadTime();
// Now we add events
// We're interested in these filetypes so keep this here
var filetypes = /\.(pdf|flv|mp4|wmv|mov|doc*|ppt* )$/i;
// loop though each anchor element on the current page
$( 'a[href]' ).each( function(){
// cache the href attribute and the class of the anchor element
var href = this.href,
cls = this.getAttribute( "class" ); // optimization
// Long if() statement below.
// check for links starting with http or https, making sure that links to our own domain are excluded
if ( ( href.match( /^https?\:/i ) ) && ( !href.match( document.domain ) ) ){
$( this ).click( function() {
var extLink = href.replace( /^https?\:\/\//i, '' );
// log a click to an external site, and the site's URL
pageTracker._trackEvent( 'External', 'Click - External Site', extLink );
} );
}
// User clicks a horizontal menu pad
else if ( cls && cls.match( "hmpad" ) ) {
$( this ).click( function() {
var filePath = href.replace( /^https?\:\/\/(www.)*/i, '' );
pageTracker._trackEvent( 'Horizontal Menu', 'Click - Horiz. Menu Pad', filePath );
} );
}
// User clicks a horizontal menu bar
else if ( cls && cls.match( "hmbar" ) ) {
$( this ).click( function() {
var filePath = href.replace( /^https?\:\/\/(www.)*/i, '' );
pageTracker._trackEvent( 'Horizontal Menu', 'Click - Horiz. Menu Bar', filePath );
} );
}
// Vertical menu pads
else if ( cls && cls.match( "vmpad" ) ) {
$( this ).click( function() {
var filePath = href.replace( /^https?\:\/\/(www.)*/i, '' );
pageTracker._trackEvent( 'Vertical Menu', 'Click - Vertical Menu', filePath );
} );
}
//check for links starting with mailto:
else if ( href.match( /^mailto\:/i ) ){
$( this ).click( function() {
var mailLink = href.replace( /^mailto\:/i, '' );
pageTracker._trackEvent( 'Email', 'Click - Email', mailLink );
} );
}
//check for links with file extension that match the filetypes regular expression:
else if ( href.match( filetypes ) ){
$( this ).click( function() {
var extension = ( /[.]/.exec( href ) ) ? /[^.]+$/.exec( href ) : undefined;
var filePath = href.replace( /^https?\:\/\/(www.)*/i, '' );
pageTracker._trackEvent( 'Download', 'Click - ' + extension, filePath );
} );
}
} );
} catch( err ){}
});
});