Last active
May 16, 2024 08:21
-
-
Save stravid/5772314 to your computer and use it in GitHub Desktop.
A simple way to track how far users are scrolling. Assumes you are using Mixpanel and jQuery. Copyright © 2013 David Strauß
MIT License
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
new MixpanelScrollTracker({ | |
attribute: 'section', | |
event: 'Scrolled to', | |
markers: [ | |
{ position: 500, value: 'Services' }, | |
{ position: 700, value: 'About Us' }, | |
{ position: 900, value: 'Contact Form' } | |
] | |
}); |
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
class MixpanelScrollTracker | |
constructor: (options) -> | |
@markers = options.markers.sort @compareMarkers | |
@event = options.event | |
@attribute = options.attribute | |
@intervalID = setInterval @tick, 500 | |
tick: => | |
currentPosition = $(window).scrollTop() | |
while @markers.length > 0 && currentPosition >= @markers[0].position | |
mixpanelObject = {} | |
mixpanelObject[@attribute] = @markers[0].value | |
mixpanel.track @event, mixpanelObject | |
@markers.shift() | |
@stopTracking() if @lastMarkerIsReached() | |
compareMarkers: (a, b) -> a.position >= b.position ? -1 : 1 | |
lastMarkerIsReached: -> @markers.length == 0 | |
stopTracking: -> clearInterval @intervalID | |
window.MixpanelScrollTracker = MixpanelScrollTracker |
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
(function(){var t,r=function(t,r){return function(){return t.apply(r,arguments)}};t=function(){function t(t){this.tick=r(this.tick,this),this.markers=t.markers.sort(this.compareMarkers),this.event=t.event,this.attribute=t.attribute,this.intervalID=setInterval(this.tick,500)}return t.prototype.tick=function(){var t,r;for(t=$(window).scrollTop();this.markers.length>0&&t>=this.markers[0].position;)r={},r[this.attribute]=this.markers[0].value,mixpanel.track(this.event,r),this.markers.shift();return this.lastMarkerIsReached()?this.stopTracking():void 0},t.prototype.compareMarkers=function(t,r){var i;return null!=(i=t.position>=r.position)?i:-{1:1}},t.prototype.lastMarkerIsReached=function(){return 0===this.markers.length},t.prototype.stopTracking=function(){return clearInterval(this.intervalID)},t}(),window.MixpanelScrollTracker=t}).call(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment