Skip to content

Instantly share code, notes, and snippets.

@restlessmedia
Last active August 29, 2015 14:11
Show Gist options
  • Save restlessmedia/12a249faf2007870500f to your computer and use it in GitHub Desktop.
Save restlessmedia/12a249faf2007870500f to your computer and use it in GitHub Desktop.
scrolly a window scroll listener
var scrolly = (function () {
var isDrag = false;
var lag = 100;
var isMouseDown = false;
var listeners = {};
var previous;
var Bounce = function (delegate, lag) {
var that = this;
return function () {
if (that.timer) {
clearTimeout(that.timer);
}
that.timer = setTimeout(delegate, lag);
}
};
var onMouseDown = function () {
isMouseDown = true;
};
var onMouseUp = function () {
isMouseDown = false;
if (isDrag) {
isDrag = false;
trigger('stop');
}
};
var onScroll = function () {
if (isDrag) {
previous = window.pageYOffset;
return;
}
if (isMouseDown) {
isDrag = isMouseDown;
trigger('start');
previous = window.pageYOffset;
return;
}
if (window.pageYOffset == previous) {
return;
}
trigger('start');
trigger('stop');
previous = window.pageYOffset;
};
var forEachListener = function (type, delegate) {
if (!listeners[type]) {
return;
}
for (var i = 0; i < listeners[type].length; i++) {
if (delegate.call(listeners[type][i], i) === false) {
break;
}
}
};
var trigger = function (type) {
var that = this;
forEachListener(type, function () {
this(window.pageYOffset);
});
};
var on = function (type, delegate) {
if (!listeners[type]) {
listeners[type] = [];
}
listeners[type].push(delegate);
};
var off = function (type, delegate) {
forEachListener(type, function (i) {
if (this === delegate) {
delete listeners[type][i];
}
});
};
var toggle = function (threshold, inside, outside, isAuto) {
on('stop', function (y) {
var inThreshold = y < threshold;
if ((isAuto !== false && (previous > y || inThreshold)) || (!isAuto && inThreshold)) {
inside(y);
} else {
outside(y);
}
})
};
var init = function () {
window.onscroll = new Bounce(onScroll, lag);
document.onmousedown = onMouseDown;
document.onmouseup = onMouseUp;
};
init();
return{
on: on,
off: off,
toggle: toggle
}
})();
@restlessmedia
Copy link
Author

scrolly.toggle(200, function () {
document.body.className = 'header';
}, function () {
document.body.className = 'header idle';
});

scrolly.on('start', function(){
console.log('start 1')
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment