/*! * jquery.scrolldepth.js | v0.1.1 * Copyright (c) 2012 Rob Flaherty (@robflaherty) * Licensed under the MIT and GPL licenses. */ ;(function ( $, window, document, undefined ) { "use strict"; var defaults = { elements: [], minHeight: 0, offset: 0, // Not used yet percentage: true, testing: false }, $window = $(window), cache = []; /* * Plugin */ $.scrollDepth = function(options) { options = $.extend({}, defaults, options); // Return early if document height is too small if ( $(document).height() < options.minHeight ) { return; } // Establish baseline (0% scroll) sendEvent('Percentage', 'Baseline'); /* * Functions */ function sendEvent(action, label) { if (!options.testing) { _gaq.push(['_trackEvent', 'Scroll Depth', location.pathname, label, 1, true]); } else { $('#console').html(action + ': ' + label); } } function calculateMarks(docHeight) { /* modified on 2014.06.23 */ /* track scroll depth every 10% */ return { '10%' : parseInt(docHeight * 0.10, 10), '20%' : parseInt(docHeight * 0.20, 10), '30%' : parseInt(docHeight * 0.30, 10), '40%' : parseInt(docHeight * 0.40, 10), '50%' : parseInt(docHeight * 0.50, 10), '60%' : parseInt(docHeight * 0.60, 10), '70%' : parseInt(docHeight * 0.70, 10), '80%' : parseInt(docHeight * 0.80, 10), '90%' : parseInt(docHeight * 0.90, 10), /*'25%' : parseInt(docHeight * 0.25, 10), '50%' : parseInt(docHeight * 0.50, 10), '75%' : parseInt(docHeight * 0.75, 10),*/ // 1px cushion to trigger 100% event in iOS '100%': docHeight - 1 }; } function checkMarks(marks, scrollDistance) { // Check each active mark $.each(marks, function(key, val) { if ( $.inArray(key, cache) === -1 && scrollDistance >= val ) { sendEvent('Percentage', key); cache.push(key); } }); } function checkElements(elements, scrollDistance) { $.each(elements, function(index, elem) { if ( $.inArray(elem, cache) === -1 && $(elem).length ) { if ( scrollDistance >= $(elem).offset().top ) { sendEvent('Elements', elem); cache.push(elem); } } }); } /* * Scroll Event */ $window.on('scroll.scrollDepth', function() { /* * We calculate document and window height on each scroll event to * account for dynamic DOM changes. */ var docHeight = $(document).height(), winHeight = window.innerHeight ? window.innerHeight : $window.height(), scrollDistance = $window.scrollTop() + winHeight, // Offset not being used yet offset = parseInt(winHeight * (options.offset / 100), 10), // Recalculate percentage marks marks = calculateMarks(docHeight); // If all marks already hit, unbind scroll event if (cache.length >= 10 + options.elements.length) { $window.off('scroll.scrollDepth'); return; } // Check specified DOM elements if (options.elements) { checkElements(options.elements, scrollDistance); } // Check standard marks if (options.percentage) { checkMarks(marks, scrollDistance); } }); }; })( jQuery, window, document );