I have an application which lets the user open several draggable popups. I don’t want to use jQuery UI and below is the code so far. However, when dragging a div it gets centered to the pointer, and that’s not how it should be done.
Actually, what I want to accomplish is that it should only be able to drag the window by clicking on the top div (se illustration below).
function endMove() {
$(this).removeClass('movable');
}
function startMove() {
$('.movable').mousemove(function(event) {
var thisX = event.pageX - $(this).width() / 2,
thisY = event.pageY - $(this).height() / 2;
$('.movable').offset({
left: thisX,
top: thisY
});
});
}
$(document).ready(function() {
$("#containerDiv").click(function() {
$(this).addClass('movable');
startMove();
}).mouseup(function() {
$(this).removeClass('movable');
endMove();
});
});
If your divs are laid out so there is a container with a header and a content area nested inside then I think you could make the following changes to bind the click handling to the header but apply the movement to the container. Also, you need to capture the initial location of the click and calculate your movement deltas starting from there in order to avoid causing the div to jump:
I haven’t tested this thoroughly, but it seems to work pretty well in a quick test page.