I have an element that can be dragged up/down. If the user is at the top of the page, the element (div) will stop dragging when it gets 50px from the top (same for bottom if user is scrolled all the way to the bottom).
The Problem: If the user scrolls down the page just a little then the div can be dragged out of view. I would like for it to stop before it goes out of view from the top and the bottom. Picture cell phone screen, you can drag a little box on right side of your screen up/down, but can't drag it out of view, even when you scroll up/down the page.
I know I need to figure out whether the page is scrolled then subtract that from the document height, etc, etc...(or something like that). Or maybe there is a better solution I don't know about.
Here is what I have so far that makes the div draggable along the y axis:
this.makeDraggable = function(){
var docHeight = $(document).height();
var winHeight = $(window).height();
if(eventSupported('touchstart')){
el.addEventListener("touchmove", handleMove, false);
}
function handleMove(e) {
e.preventDefault();
var y = e.changedTouches[0].pageY;
var bottom = winHeight - y;
if(bottom > 50 && y > 50)
$el.offset({
top: y
});
}
}
Found the solution:
this.makeDraggable = function(){
var docHeight = $(document).height();
var winHeight = $(window).height();
if(eventSupported('touchstart')){
el.addEventListener("touchmove", handleMove, false);
}
function handleMove(e) {
e.preventDefault();
var winScroll = $(window).scrollTop(); // scrolled away from top
var y = e.changedTouches[0].pageY;
var top = winScroll + 50;
var bottom = winScroll + winHeight - 50;
if(bottom > y && y > top)
$el.offset({
top: y
});
}
}
$(window).scrollTop() + $(window).height() is always going to be the bottom of the "window".