Scroll window when an item is dragged close to the top or bottom.
I could not get any of the other answers working. Using Chrome and a sortable grid that needs to scroll vertically when an item is being dragged to the top or bottom edge of the window.
NOTE: This only works for scrolling the entire window. This will not work if you have a scrollable section inside of the window and need to scroll that.
I was able to get the following working flawlessly:
var currentlyScrolling = false;
var SCROLL_AREA_HEIGHT = 40; // Distance from window's top and bottom edge.
$(".sortable").sortable({
scroll: true,
sort: function(event, ui) {
if (currentlyScrolling) {
return;
}
var windowHeight = $(window).height();
var mouseYPosition = event.clientY;
if (mouseYPosition < SCROLL_AREA_HEIGHT) {
currentlyScrolling = true;
$('html, body').animate({
scrollTop: "-=" + windowHeight / 2 + "px" // Scroll up half of window height.
},
400, // 400ms animation.
function() {
currentlyScrolling = false;
});
} else if (mouseYPosition > (windowHeight - SCROLL_AREA_HEIGHT)) {
currentlyScrolling = true;
$('html, body').animate({
scrollTop: "+=" + windowHeight / 2 + "px" // Scroll down half of window height.
},
400, // 400ms animation.
function() {
currentlyScrolling = false;
});
}
}
});
Coffeescript Version
currentlyScrolling = false
SCROLL_AREA_HEIGHT = 40
sort: (event, ui) ->
return if currentlyScrolling
windowHeight = $( window ).height()
mouseYPosition = event.clientY
if mouseYPosition < SCROLL_AREA_HEIGHT # Scroll up.
currentlyScrolling = true
$( 'html, body' ).animate( { scrollTop: "-=" + windowHeight / 2 + "px" }, 400, () -> currentlyScrolling = false )
else if mouseYPosition > ( windowHeight - SCROLL_AREA_HEIGHT ) # Scroll down.
currentlyScrolling = true
$( 'html, body' ).animate( { scrollTop: "+=" + windowHeight / 2 + "px" }, 400, () -> currentlyScrolling = false )