JavaScript drag`n drop is very simple thing. Last week some juniors ask me how they can drag a div element. Then I thought to write this simple post..
To Drag a div it needs 3 mouse events onmousedown, onmousemove and onmouseup. These three events can do all the job.
Live example here at
http://www.apueee.com/tma_examples/dragit_tma.htm
Javascript Code Here :
<script type="text/javascript">
//initiate variables
var element;
var DragNow = false;
var dx=0;
var dy=0;
function initDrag(e)
{
e = (e)? e : event;
DragNow = true;
dx = Math.abs(parseInt(element.style.left) - e.clientX);
dy = Math.abs(parseInt(element.style.top) - e.clientY);
//declare mousemove and mouseup event
document.onmousemove = startDrag;
document.onmouseup = stopDrag;
}
function stopDrag()
{
DragNow = false;
}
function startDrag(e)
{
e = (e)? e : event;
if(DragNow)
{
element.style.top = (e.clientY - dy) + 'px';
element.style.left = (e.clientX - dx) + 'px';
}
}
window.onload = function()
{
//set the draggable element
element = document.getElementById(elementId);
//initiate mousedown event
element.onmousedown = initDrag;
}
</script>
Here the important thing is that the position of the element must
be 'absolute'.
That's all about the drag`n drop.
Add New Comment
Viewing 4 Comments
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Add New Comment
Trackbacks