How to drag something using JavaScript

Web programming topics
Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to drag something using JavaScript

Post by Saman » Thu Mar 11, 2010 11:40 am

Drag-and-drop is one of the most important components. This tutorial describes a simple method for implementing drag-and-drop functionality in a web page using JavaScript.

Set up
We need to set up a few things before getting into the actual dragging code. We will need an object that is to be dragged. In this example, there will be only one draggable object, but it could be expanded to include unlimited draggable objects. We are using a div element, but the same could apply to any visible element such as an img.

First, the object needs some CSS styling. For this demo, we have given it a green background and nice bevelled border. It also needs to be set to position:absolute; so that it is free from the document cascade and can be positioned at will anywhere in the browser window.

We need a few things to happen in the JavaScript on page load. We set document.onmousemove and document.onmouseup to run our functions as these events are each triggered. These functions will be described shortly.

We also set up some globals and run an initialise function. The position of the drag object is set in this function so that the left and top properties are initialised. You could position it in the CSS, but then you would not have access to these values via JavaScript.

The object is set to display:none in the CSS and then display:block in the javascript. This is so that it will be invisible until it is ready to be dragged.

The ondrag and onselectstart settings are to stop Internet Explorer misbehaving. These are IE specific methods that have control over the behaviour of click-and-drag actions. By setting them to an empty function, they are disabled. Otherwise, Internet Explorer thinks you want to select text and will start highlighting things.

Code: Select all

var dragObject, offsetX, offsetY, isDragging=false;
window.onload = init;
document.onmousemove = mM;
document.onmouseup = mU;

function init() {
    var ob = document.getElementById("dragObject");

    ob.ondrag=function(){return false;};
    ob.onselectstart=function(){return false;};

    ob.style.left="100px";
    ob.style.top="100px";
    ob.style.display="block";
}
 
Mouse down event
Once you have set up, the drag-and-drop is controlled by three DOM events: onmousedown, onmousemove, and onmouseup. First of all, we want to detect an onmousedown on the drag object. Our own function will be assigned to the drag object to run when the mouse is clicked down.

There are a number of ways to assign a function to the event. The simplest way is to use the onmousedown attribute that can be defined in the HTML:

Code: Select all

<div onmousedown="javascript: mD(this,event);"></div> 
The this argument is a pointer to the object that was clicked. The event argument passes through a reference to the event object itself. This contains all kinds of data that are part of the mouse down event. Internet Explorer has it’s own way of accessing the event object via window.event.

Code: Select all

function mD(dragObject, e) {
    if (window.event) e=window.event;
    //mouse down handling...
} 
We need to know the position of the mouse as well as the position of the drag object. The position of the mouse is contained in the event object as clientX and clientY. The position of the drag object can be accessed via style.left and style.top which we transform from strings to integers using parseInt. With these four values, we calculate the distance between the mouse and the top-left of the drag object.

We also set the global isDragging to true. This will let the other functions know that a drag is in action.

We end each of the mouse handlers with return false. This means that the event itself is halted and no other browser or operating system behaviours will occur.

Code: Select all

function mD(ob,e) {
    dragObject = ob;

    if (window.event) e=window.event;

    var dragX = parseInt(dragObject.style.left);
    var dragY = parseInt(dragObject.style.top);

    var mouseX = e.clientX;
    var mouseY = e.clientY;

    offsetX = mouseX - dragX;
    offsetY = mouseY - dragY;

    isDragging = true;

    return false;
} 
Mouse move event
The mM function will run every time the mouse is moved. We only want to do something if the object is being dragged. We quickly exit the function if there is no dragging in action by saying return.

If the object is being dragged, we want to reposition it to be below the mouse pointer. Once again, we access the mouse position via event.clientX and event.clientY. Using the offsets that were calculated in mD, we reposition our drag object:

Code: Select all

function mM(e) {
    if (!isDragging) return;

    if (window.event) e=window.event;

    var newX = e.clientX - offsetX;
    var newY = e.clientY - offsetY;

    dragObject.style.left = newX + "px";
    dragObject.style.top = newY + "px";

    return false;
} 
Mouse up event
The drag needs to be halted on mouseup. All we need to do is set isDragging to false and the dragging will end.

Code: Select all

function mU() {
    if (!isDragging) return;
    isDragging = false;
    return false;
} 
Post Reply

Return to “Web programming”