Skip to content

Instantly share code, notes, and snippets.

@dbp
Created August 16, 2013 01:11
Show Gist options
  • Save dbp/6246396 to your computer and use it in GitHub Desktop.
Save dbp/6246396 to your computer and use it in GitHub Desktop.
simple discrete scrolling
$(function () {
for(var i = 0; i < 10; i++) {
$("#active").append($("<div class='elem'>Block " + i + "</div>"));
}
$("#pointer").bind("mousedown", start);
});
function start(event) {
window.startpos = parseInt($("#pointer").css("top"));
$(document).bind("mousemove", drag);
$(document).bind("mouseup", end);
}
function drag(event) {
// First, keep the pointer in the right place
var top = $("#scroll").offset().top;
var height = $("#scroll").height();
var pos = event.pageY - top;
if (pos < 0) {
pos = 0;
} else if (pos > height) {
pos = height;
}
$("#pointer").css("top", pos + "px");
// Now, figure out if we need to scroll.
var diff = window.startpos - pos;
if (diff < 0) { // moving down
var fraction = -diff / (height - pos);
console.log("fraction: " + fraction);
var nextElem = $("#active .elem").first();
var total = $("#active")[0].scrollHeight;
if (fraction > nextElem.height()/total) {
$("#inactive").append(nextElem);
window.startpos = pos;
}
} else { // moving up
var fraction = diff / pos;
var nextElem = $("#inactive .elem").last();
var total = $("#inactive")[0].scrollHeight;
if (fraction > nextElem.height()/total) {
$("#active").prepend(nextElem);
window.startpos = pos;
}
}
}
function end(event) {
$(document).unbind("mousemove", drag);
$(document).unbind("mouseup", end);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment