I have this code:
jQuery:
var mouseDown=false;
var lastPositionX;
var lastPositionY;
var newX;
var newY;
var lastPositionLeft;
var lastPositionTop;
var newLeft;
var newTop;
$("#insideMap").on("mousedown",function(){
mouseDown=true;
lastPositionX=e.pageX;
lastPositionY=e.pageY;
});
$("#insideMap").on("mouseup",function(u){
mouseDown=false;
});
$("#insideMap").on("mouseleave",function(){
mouseDown=false;
});
$("#insideMap").on("mousemove",function(n){
if (mouseDown){
mouseDown = true; // mantain the boolean to prevent mouseleave trigger
newX=n.pageX-lastPositionX;
newY=n.pageY-lastPositionY;
lastPositionLeft=$("#insideMap").position().left;
lastPositionTop=$("#insideMap").position().top;
newLeft=newX+lastPositionLeft;
newTop=newY+lastPositionTop;
$("#insideMap").css({"left":newLeft,"top":newTop});
lastPositionX=n.pageX;
lastPositionY=n.pageY;
}
});
Demo: http://jsfiddle.net/SkWeX/3/
but something is still bad :( it doesnt work well, it is still lagging, can you help me with it?
:) the browser wants sometimes to drag your image (bg), you need to prevent this!
Just add this to your #insideMap
element's CSS:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
And this code is all you need:
var mouseDown=false,
posX = 0,
posY = 0,
innerX = 0,
innerY = 0;
$("#insideMap").on("mousedown",function(e){
innerX = e.pageX - $(this).offset().left;
innerY = e.pageY - $(this).offset().top;
mouseDown= true;
}).on("mouseup",function(){
mouseDown=false;
});
$(document).on("mousemove",function(e){
if (mouseDown){
var m = { x: e.pageX-innerX, y: e.pageY-innerY };
$('#insideMap').css({ left: m.x, top: m.y });
}
});
Some explanation:
Your code is slow cause on any registered mousemovement (and there are many) you are recalculating the element position. Wrong.
innerX
and innerX
CSS element position
to the actual mouse position (you guess right: ) but minus the position where the element was clicked (innerX, innerY) (to prevent the element jump to mouse position) .