I'm trying to achieve dragging effect on a div element using jQuery. This div element is usually hidden and pops up when triggered.
The following algorithm works fine if I haven't scrolled on my document. When I scroll, say, X pixels down my document, then the newTop
value somehow add this offset and the div moves X pixels below the mouse position.
I believe that it is because window_div.offset().top
returns the position of the div from the very top of the document even if it is floating. Is there any way to get the div's position from the TOP of the SCREEN?
or is there any other solution?
make_window_draggable(window_div) {
var bWindowMoveMouseDown = false;
var windowPositionLeft = 0;
var windowPositionTop = 0;
var initMousePositionLeft = 0;
var initMousePositionTop = 0;
var newMousePositionLeft = 0;
var newMousePositionTop = 0;
window_div.bind('mousedown', function(e) {
windowPositionLeft = window_div.offset().left;
windowPositionTop = window_div.offset().top;
initMousePositionLeft = e.screenX;
initMousePositionTop = e.screenY;
bWindowMoveMouseDown = true;
});
$(document).bind('mousemove',function(e) {
if(bWindowMoveMouseDown) {
newMousePositionLeft = e.screenX;
newMousePositionTop = e.screenY;
let relativeMouseLeft = newMousePositionLeft - initMousePositionLeft;
let relativeMouseTop = newMousePositionTop - initMousePositionTop;
var newLeft = windowPositionLeft + relativeMouseLeft;
var newTop = windowPositionTop + relativeMouseTop;
//check bounds
window_div.css({
left:newLeft,
top:newTop
});
}
});
window_div.bind('mouseup', function(e) {
bWindowMoveMouseDown = false;
});
}