Created
May 1, 2014 14:29
-
-
Save tannerhodges/4e5a890809ded1d81d4d to your computer and use it in GitHub Desktop.
GA Tracking for jQuery Slideshow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function() { | |
// Default tracking settings | |
var slider_event = 'slide'; | |
var slider_source = 'navigation'; | |
// Create slideshow instances | |
var $s = $('.slideshow').slides({ | |
onupdate: function(slide_index) { | |
// Track based on slider_event | |
if (slider_source !== 'link') { | |
ga_track_events(slider_event, slider_source, slide_index); | |
} | |
// Reset tracking settings | |
slider_event = 'slide'; | |
slider_source = 'navigation'; | |
} | |
}); | |
// Set click event for tracking | |
$('[data-slides], .slide a').on('click', function(e) { | |
// Set event to 'clicked' | |
slider_event = 'clicked'; | |
// Determine whether click was navigation or link | |
slider_source = $(this).data('slides') !== undefined ? $(this).data('slides') : 'link'; | |
// If click was link, track event now | |
// Otherwise, let slides callback handle tracking | |
if (slider_source === 'link') { | |
var current_slide = $('.slides-pagination .selected a').first().html() - 1; | |
ga_track_events(slider_event, slider_source, current_slide); | |
// Reset tracking settings | |
slider_event = 'slide'; | |
slider_source = 'navigation'; | |
} | |
}); | |
// Access an instance API | |
api = $s.eq(0).data('slides'); | |
// Transition select | |
$('select[name=transition]').on('change', function() { | |
api.redraw( this.value ); | |
}); | |
// $('.carousel_root').carousel(); | |
$('.carousel').carousel(); | |
}); | |
/** | |
* Track slide events for Google Analytics | |
* @param {string} event | |
* @param {string} source | |
* @param {int} slide_index | |
*/ | |
function ga_track_events(event, source, slide_index) { | |
// Data | |
var $slides = $('.slideshow .slide'); | |
var slide = slide_index + 1; | |
var name = $slides[slide_index].children[0].children[0].alt; | |
var label = '[' + slide + ']-[' + name + ']'; | |
// Action | |
var action = ''; | |
if ( event === 'slide' ) { | |
action = 'slideChanged'; | |
} | |
else if ( source === 'link' ) { | |
action = 'slideClicked'; | |
} | |
else if ( source === 'next' ) { | |
action = 'rightArrow'; | |
} | |
else if ( source === 'previous' ) { | |
action = 'leftArrow'; | |
} | |
else { | |
action = 'number'; | |
} | |
// Tracking | |
ga('send', 'event', 'homepage_carousel', action, label); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment