Skip to content

Instantly share code, notes, and snippets.

@gaearon
Created October 24, 2014 16:47
Show Gist options
  • Save gaearon/150fa1bed09c92abdb46 to your computer and use it in GitHub Desktop.
Save gaearon/150fa1bed09c92abdb46 to your computer and use it in GitHub Desktop.
Scroll on drag with react-dnd
configureDragDrop(registerType) {
var imageThreshold = Math.max(120, window.innerHeight / 4),
sectionThreshold = Math.max(140, window.innerHeight / 4),
currentDY = 0,
frame;
function makeScrollingHandler(threshold) {
function getScrollDY(clientY) {
var speed;
if (clientY < threshold) {
// -1 to 0 as we move from 0 to threshold
speed = -1 + clientY / threshold;
} else if (clientY > window.innerHeight - threshold) {
// 0 to 1 as we move from (innerHeight - threshold) to innerHeight
speed = 1 - (window.innerHeight - clientY) / threshold;
} else {
speed = 0;
}
return Math.round(speed * 10);
}
function tick() {
if (!currentDY) {
frame = null;
return;
}
window.scrollTo(0, getScrollY() + currentDY);
frame = window.requestAnimationFrame(tick);
}
function queueScroll(dy) {
currentDY = dy;
if (!frame) {
frame = window.requestAnimationFrame(tick);
}
}
function cancelScroll() {
window.cancelAnimationFrame(frame);
frame = null;
currentDY = 0;
}
return {
dropTarget: {
enter: cancelScroll,
leave: cancelScroll,
over(item, e) {
queueScroll(getScrollDY(e.clientY));
},
acceptDrop() {
cancelScroll();
return false;
}
}
};
}
registerType(DragItemTypes.SECTION, makeScrollingHandler(sectionThreshold));
registerType(DragItemTypes.IMAGE, makeScrollingHandler(imageThreshold));
},
@iDVB
Copy link

iDVB commented Oct 27, 2015

Found this while searching for a way to autoscroll the parent element of scrollable items while dragging.
Is there a thread or more details on how to use this?

@dshorowitz
Copy link

+1. How do you use this code? Thanks in advance!

@flushentitypacket
Copy link

Seems like a lot of folks (including me!) are landing here from search engines, so I thought I'd try to be helpful by dropping a solution here that doesn't depend on react-dnd: https://gist.github.com/flushentitypacket/7717cb30d1b172e633cea864eeb4d2e7

May not be the exact feature set folks are looking for, but should provide a good starting point! Hope this helps someone.

@useafterfree
Copy link

@gaearon Does this still work?

@call3hudson
Copy link

yeah, I tried recently

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