I’m having a bit trouble here with creating a map for a browser based game like Travian. I have created a function which drags the map into different directions, but each time I click on a different position than where I released the mouse on it directly changes position and then I can move it as I want. Is there any way of solving this? Is JQuery needed? (I’m not so good at Javascript so my code might be a bit different than what the easy way around code would look like)
Full document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Map</title>
<script type="text/javascript">
//object of the element to be moved
_item = null;
//stores x & y co-ordinates of the mouse pointer
mouse_x = 0;
mouse_y = 0;
// stores top,left values (edge) of the element
mapdiv_x = 0;
mapdiv_y = 0;
//bind the functions
function move_init()
{
document.onmousemove = _move;
document.onmouseup = _stop;
}
//destroy the object when we are done
function _stop()
{
_item = null;
}
//main functions which is responsible for moving the element (div in our example)
function _move(e)
{
mouse_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("mapdiv").backgroundPositionX;
mouse_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("mapdiv").backgroundPositionY;
if(_item != null)
{
_item.style.backgroundPosition = "-" + (mouse_x - mapdiv_x) + "px -" + (mouse_y - mapdiv_y) + "px";
}
}
//will be called when use starts dragging an element
function _move_item(mapdiv)
{
//store the object of the element which needs to be moved
_item = mapdiv;
mouse_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("mapdiv").backgroundPositionX;
mouse_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("mapdiv").backgroundPositionY;
oldmapdivx = _item.style.backgroundPositionX;
oldmapdivy = _item.style.backgroundPositionY;
mapdiv_x = oldmapdivx - mouse_x;
mapdiv_y = oldmapdivy - mouse_y;
mapdivx2 = mouse_x - mapdiv_x;
mapdivy2 = mouse_y - mapdiv_y;
}
</script>
<style type="text/css">
#mapdiv {
background-image:url('images/map.png');
background-repeat:no-repeat;
background-color:#666;
width:750px;
height:500px;
cursor: move;
}
</style>
</head>
<body onload="move_init()">
<div id="mapdiv" onmousedown="_move_item(this);"></div>
</body>
</html>
I can’t see the issue in your code, unfortunately.
If you’re not dead set on writing your own code for this, though, there is actually a really nice Jquery plugin that does exactly what you seem to want. It’s called Overscroll (http://www.azoffdesign.com/overscroll) and provides you with all the features you’d need for a system like this. Give it a look, I’ve found it really useful in my own work in the past. Looking through the code might also help you find the issue in your own solution, as well.