How to drag something

March 15th, 2006 in Basic Tutorials · By David Tapper

Drag-and-drop is one of the most important components of TheBroth. 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.

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:

<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.

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.

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:

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.

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

Final example

Click here to see the entire JavaScript dragging example in action. Feel free to make use of the code!

Share this:
  • del.icio.us
  • StumbleUpon
  • Furl
  • Netscape
  • Reddit
  • Technorati
  • YahooMyWeb

12 Responses to “How to drag something”

Jason24 Jun 06

I’m looking for a little something here… how do you use make these kinds of scripts so that the right-click is still useable as usual?

Ryx26 Jul 06

I like that you have the code written out so others can learn from your site.
Although, if I’m gonna code a game or something I’m gonna try PHP or flash first.

juliff17 Oct 06

The example deosn’t work

Markus17 Oct 06

Sorry, the link wasn’t working for a few days and we didn’t notice. Thanks for bringing it up, it’s fixed now. The example itself works just fine, btw :-)

Adam Kid11 Dec 06

You people need to make sure you know this!

KrishKeyan1 Feb 07

Excellent….

Mike Rumble13 Feb 07

Found this article through Google.

I’ve been working on some drag and drop stuff of my own recently and somewhat unsurprisingly IE was mis-behaving.

The ondrag and onselect stuff you wrote about did the trick so thanks for that, I’d not seen it mentioned elsewhere.

Morary Ionut26 Jul 07

Nice and simple example, thanks.

צביקה27 Aug 07

תודה רבה על ההסבר הבהיר והמוצלח! חפשתי משהו כזה הרבה זמן [נניח]

tenk u very match on the file example

Umair19 Dec 07

Great tutorial Markus though it require redundant remarks

Biren Kumar3 Jun 08

The code written is well.
But i want to know dragging folder & folder items from a tree structure menu and i want to place it some where else in this web page.
Thanking U !

Azad5 Jul 08

Nice toturial.But i want many object to move in same page.

Leave a comment