Last active
September 30, 2017 04:54
-
-
Save benyanke/f50a4047bbdd586e8028efbb3be04626 to your computer and use it in GitHub Desktop.
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
<script> | |
// ScrollTrack.js allows a function to be run once and only once if it's seen. | |
// Ben Yanke <ben@benyanke.com> | |
// SelectorToWatch - a standard jquery element selector | |
// functionToRun - a function to be run when the selector is on screen | |
function scrollWatch(selectorToWatch, functionToRun) { | |
// Check first to see if it even exists on the page | |
if (!$(selectorToWatch).position()) { | |
return false; | |
} else { | |
console.log(selectorToWatch + " found: binding to scroll events"); | |
} | |
// Check the first time | |
if (checkIfOnScreen(selectorToWatch)) { | |
functionToRun(); | |
} else { | |
// If it's not there right away, check on every scroll | |
// Run this on every scroll event | |
var scroller = $(document).on('scroll', function() { | |
// If the tracked div is in the window, fire event | |
if (checkIfOnScreen(selectorToWatch)) { | |
// Any code in here will be run once and only once if the element is scrolled to | |
console.log("The selector '" + selectorToWatch + "' scrolled into view. Unbinding listener"); | |
functionToRun(); | |
// Ensures this never runs multiple times by unbinding the scroll event listener | |
scroller.unbind(); | |
} | |
}); | |
} | |
function checkIfOnScreen(selectorToWatch) { | |
var top_of_selectorToWatch = $(selectorToWatch).offset().top; | |
var bottom_of_selectorToWatch = $(selectorToWatch).offset().top + $(selectorToWatch).outerHeight(); | |
var bottom_of_screen = $(window).scrollTop() + $(window).height(); | |
var top_of_screen = $(window).scrollTop(); | |
if ((bottom_of_screen > top_of_selectorToWatch) && (top_of_screen < bottom_of_selectorToWatch)) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
} | |
function trackWrapper(element, title, callback) { | |
scrollWatch(element, function() { | |
// Send event to Google Analytics via Google Tag Manager - replace this with a ga() function if not in GTM | |
dataLayer.push({ | |
'event': 'gaEvent', | |
'gaEventName': 'ScrollTo: ' + title | |
}); | |
}); | |
} | |
trackWrapper('body.page-id-12775 #cutaway', '/displays/#cutaway'); | |
trackWrapper('body.page-id-12549 #Metal-Models', '/specialty-models/#Metal-Models'); | |
trackWrapper('body.page-id-12723 #mobile', '/cgi/#mobile'); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment