How to make an image draggable (Google Map Type)

How to make an image draggable (Google Map Type)

These days I am working more on JavaScript and have come across a lot of interesting features of it. In due course I made a demo page using JavaScript to make in image dragable in

element. It gives the feel of Google Map. Here is the code for the same:

Style:

#divDemo
{
overflow: hidden;
position:absolute;
top: 100px;
left: 100px;
border: 2px solid #666666;
width: 400px;
height: 300px;
cursor:pointer;
}
img
{
border: 1px solid #333333;
}

JavaScript function:

//global variables
var object = null;
var offset = null;
//capture events
document.onmousemove = mouseMove;
document.onmouseup = mouseUp;

function mousePoint(x,y)
{
this.x = x;
this.y = y;
}
//function to get current x and y position of mouse
function mousePosition(evnt)
{
var x = evnt.clientX;
var y = evnt.clientY;
return new mousePoint(x,y);
}

//function to get offset of mouse from it’s original position, say drag of mouse
function getMouseOffset(target, evnt)
{
evnt = evnt || window.event;
var mousePos = mousePosition(evnt);
var x = mousePos.x – target.offsetLeft;
var y = mousePos.y – target.offsetTop;
return new mousePoint(x,y);
}

function mouseUp(evnt)
{
object = null;
}
//function to change the position of image with movement of mouse
function mouseMove(evnt)
{
if (!object) return;
evnt = evnt || window.event;
var mousePos = mousePosition(evnt);

// if draggable, set new absolute position
if(object)
{
var top = mousePos.y – offset.y;
var left = mousePos.x – offset.x;
var right = (left + object.width) – document.getElementById(“divDemo”).clientWidth;
var bottom = (top + object.height) – document.getElementById(“divDemo”).clientHeight;
if(top <= 0 && left <= 0 && right >= 0 && bottom >= 0)
{
object.style.position = ‘absolute’;
object.style.top = top + “px”;
object.style.left = left + “px”;
return false;
}
else
{
object.style.position = ‘absolute’;
object.style.top = object.style.top;
object.style.left = object.style.left;
return false;
}
}
}
//function to make an image/element draggable
function draggable(item)
{
if(item)
{
item = document.getElementById(item);
item.onmousedown = function(evnt)
{
object = this;
offset = getMouseOffset(this, evnt);
return false;
};
}
}

Body section:

in this section you simply need to put div having id say “divDemo”. In this div put an image which is larger in size than the parent div. Give it an id say “img1”. Now call draggable function on page load with id of image as parameter. Now you are ready to run it into any browser. Right, any browser.

I found it very interesting and hope you will find it interesting too.

Leave a Reply

Your email address will not be published. Required fields are marked *