Code:
<!DOCTYPE html><!-- HTML 5 supersedes XHTML -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Drag Element</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var $dragging = null;
var moveX = 0;
var moveY = 0;
var currentX, currentY; //vars to hold reference to current X/Y event position
$(document.body).on("mousemove", function(e) {
if ($dragging) {
e.preventDefault(); //stop highlighting of text and images in some browsers during drag
var o = $dragging.offset(); //where the object is
$dragging.offset({ //where the object is + where the mouse is - where the mouse was
left: o.left + e.pageX - currentX,
top: o.top + e.pageY - currentY
});
currentX = e.pageX;//remember where the mouse pointer is now
currentY = e.pageY;
}
});
$(document.body).on("mousedown", ".drag", function (e) {
$dragging = $(e.target)
$dragging && e.preventDefault(); //stop highlighting of text and images in some browsers during drag
moveX = parseInt(e.pageX-$(this).parent().offset().left)
moveY = parseInt(e.pageY-$(this).parent().offset().top)
currentX = e.pageX; //remember where the mouse pointer is now
currentY = e.pageY;
dev("Left: "+moveX+' - Top: '+moveY)
});
$(document.body).on("mouseup", function (e) {
moveX = parseInt(e.pageX-$(this).parent().offset().left)
moveY = parseInt(e.pageY-$(this).parent().offset().top)
$dragging = null
dev("Left: "+moveX+' - Top: '+moveY)
});
});
function dev(s){
$("#dev").text(s)
}
</script>
<style>
* {margin:0;}
html,body { height:100%;}
.drag { width: 200px; height: 200px; border: 1px solid black; }
</style>
</head>
<body>
<div class="drag">Content</div>
<div id="dev"></div>
<table style="width:150%;height:150%;"><!-- HTML element to force scrollbars for the page for testing -->
<tr>
<td></td>
</tr>
</table>
</body>
</html>
Bookmarks