Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple way to track how far users are scrolling. Assumes you are using Mixpanel and jQuery. Copyright © 2013 David Strauß MIT License
new MixpanelScrollTracker({
attribute: 'section',
event: 'Scrolled to',
markers: [
{ position: 500, value: 'Services' },
{ position: 700, value: 'About Us' },
{ position: 900, value: 'Contact Form' }
]
});
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
(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
You can’t perform that action at this time.