Drag and Drop on a Shoestring

Mar 27, 2008

While a dynamic three-column layout might be the Holy Grail of the CSS world, cross-browser drag and drop may very well be a similar prize in Javascript. There are plenty of libraries out there designed to take into account every angle, but because they consider all cases, usually they're huge and sometimes even noticably slow.

So what if you just want to take care of the 95% case, use something totally self-contained and tiny at the same time? Well, just follow these six steps to make your elements real dragons! :)

Step 1 - Choose Your Element

First things first: what do you want to drag? You'll need to know how to reference it through the DOM using javascript. This is usually as easy as applying an id attribute to the element and using var elem = document.getElementById('id');. That was easy, no?

<script type="text/javascript">

window.onload = function() {
  var elem = document.getElementById('dragon');

};

</script>

...

<span id="dragon">I'm draggable!</span>

Step 2 - Apply an OnMouseDown event

To make your element draggable, all you need to apply to it is one event. It gets somewhat more complex inside the event function, but in the element context, this is all you need.

<script type="text/javascript">

window.onload = function() {
  var elem = document.getElementById('dragon');
  elem.onmousedown = function(e) {
    e = e || event;

  };
};

</script>

...

<span id="dragon">I'm draggable!</span>

e = e || event is cross-browser code so that both Opera/FF/Safari and versions of IE can all reference the event object - which is generated each time the event fires - by referencing the e variable.

Step 3 - Store Information On The Element Itself

Once the mousedown happens, a drag may or may not follow. In either case, we're going to assume one is imminent and store some useful values before we can no longer access them. First, we'll want to change the element's position CSS style to relative so we can drag it away from where it currently sits. Next, we'll want to store the current top and left styles so we know where the element will start from. (If you have previously positioned this element using right and/or bottom you'll need to use those instead). And finally, we'll want to record the position of the mouse cursor at the moment of the mousedown; we can get this information from the event object.

The trick here is that we are storing these values on the element itself. Since the element is always in context, attaching these values to the actual object we're dragging makes things quite convenient. This avoids the use of global variables which can potentially conflict with other scripts you may be using.

<script type="text/javascript">

window.onload = function() {
  var elem = document.getElementById('dragon');
  elem.onmousedown = function(e) {
    e = e || event;

    this.style.position = "relative";
    this.posX = Number(this.style.left.replace(/px/, ''));
    this.posY = Number(this.style.top.replace(/px/, ''));
    this.mouseX = e.clientX;
    this.mouseY = e.clientY;

  };
};

</script>

...

<span id="dragon">I'm draggable!</span>

Step 4 - Apply OnMouseMove and OnMouseUp Events to the Document

But aren't we moving the element? Sure we are, but we want to record all mouse movements from here on out, not just the ones which appear over the element we are dragging. For example, if you move your mouse fast enough while dragging, for some instants the cursor will be outside of the element and that event will not register with the element at all.

So instead, we'll apply the appropriate events to the document.documentElement instead. The document.documentElement is everywhere so there is no chance of us missing one of these events, unless the mouse moves entirely outside the viewport.

<script type="text/javascript">

window.onload = function() {
  var elem = document.getElementById('dragon');
  elem.onmousedown = function(e) {
    e = e || event;
    var self = this;

    this.style.position = "relative";
    this.posX = Number(this.style.left.replace(/px/, ''));
    this.posY = Number(this.style.top.replace(/px/, ''));
    this.mouseX = e.clientX;
    this.mouseY = e.clientY;

    document.documentElement.onmousemove = function(e) {
      e = e || event;

    };
    document.documentElement.onmouseup = function(e) {
      e = e || event;

      document.documentElement.onmousemove = null;
      document.documentElement.onmouseup = null;
    };
  };
};

</script>

...

<span id="dragon">I'm draggable!</span>

Two extra things to note in this addition. One is that we added two lines to the onmouseup function that apply a value of null to the onmousemove and onmouseup events of the document.documentElement. What's going on here? Well, these two lines occur as the last action of the mouseup event which cancel the functions previously set on the document.documentElement. Effectively, this just returns things to the calm and peaceful way they used to be.

The second addition is the var self = this line. We do this so that we have a variable to refer to the draggable element once we go inside the two document.documentElement functions. Once we are inside these functions, the variable this becomes a reference to the function's parent - in other words the document.documentElement itself - and it's previous meaning will be lost. By assigning the this variable to another variable (and the name self isn't special in this regard, I could have called it anything) we can then use it as a reference to the element from within the enclosed functions.

The skeleton of our drag and drop routine is now done! Nothing visual happens at the moment, but if you try dragging the element in a browser window, all the events required to perform a dragging action are firing away. Now we just have to do something visual with all those events.

Step 5 - Assume The Position

Now we're getting somewhere. All we need to do now is appropriately position the draggable element each time we recieve a new mousemove event with updated mouse cursor coordinates.

In doing this, we're going to have to get through some basic algebra, but hopefully you should understand it without any trouble. When the mousedown event was received, we recorded the position of the mouse. When we receive a mousemove event, we again receive the position of the mouse. If we subtract one value from the other (x-coord - x-coord and y-coord - y-coord) we end up with a value which tells us how far away from the starting point the mouse has moved. We use these values to adjust the original top and left styles - which we also recorded - to move our draggable element around the screen!

<script type="text/javascript">

window.onload = function() {
  var elem = document.getElementById('dragon');
  elem.onmousedown = function(e) {
    e = e || event;
    var self = this;

    this.style.position = "relative";
    this.posX = Number(this.style.left.replace(/px/, ''));
    this.posY = Number(this.style.top.replace(/px/, ''));
    this.mouseX = e.clientX;
    this.mouseY = e.clientY;

    document.documentElement.onmousemove = function(e) {
      e = e || event;

      self.style.left = (e.clientX - self.mouseX + self.posX) + "px";
      self.style.top = (e.clientY - self.mouseY + self.posY) + "px";
    };
    document.documentElement.onmouseup = function(e) {
      e = e || event;

      document.documentElement.onmousemove = null;
      document.documentElement.onmouseup = null;
    };
  };
};

</script>

...

<span id="dragon">I'm draggable!</span>

You know what? You're done! The code above works passably in Opera, Firefox, IE6 & 7, and Safari. And you thought more was required for drag and drop?

Step 6 - Customise

The code can be used as a starting point to create a full-featured drag and drop interface, implementing such things as limits (apply max and min to left and top in the onmousemove function) and/or actions to be performed on drop (execute statements within the onmouseup function). For example, here is a modification of the code above which tells you the distance you moved the element, and also returns it to its original position.

<script type="text/javascript">

window.onload = function() {
  var elem = document.getElementById('dragon');
  elem.onmousedown = function(e) {
    e = e || event;
    var self = this;

    this.style.position = "relative";
    this.posX = Number(this.style.left.replace(/px/, ''));
    this.posY = Number(this.style.top.replace(/px/, ''));
    this.mouseX = e.clientX;
    this.mouseY = e.clientY;

    document.documentElement.onmousemove = function(e) {
      e = e || event;

      self.style.left = (e.clientX - self.mouseX + self.posX) + "px";
      self.style.top = (e.clientY - self.mouseY + self.posY) + "px";
    };
    document.documentElement.onmouseup = function(e) {
      e = e || event;

      self.style.left = "0px";
      self.style.top = "0px";
      
      document.documentElement.onmousemove = null;
      document.documentElement.onmouseup = null;

      var distance = Math.round(Math.sqrt(
        Math.pow(e.clientX - self.mouseX, 2) +
        Math.pow(e.clientY - self.mouseY, 2)
      ));

      alert("You dragged the element a distance of " + 
             distance + " pixels!");
    };
  };
};

</script>

...

<span id="dragon">I'm draggable!</span>

Keep in mind that this code only applies to one particular case. If the element you're starting with is already absolutely positioned, you'll have to prepare it differently. You may need to find out the element's actual position within the document rather than relying only on recording the distance the mouse has moved. This handy function from Quirksmode.org can help with that.

If you need to know where an element was dropped, that is a whole other can of worms. The easiest situation is if your potential target elements are in fixed and absolute positions relative to the element you're dragging. So you can tell over which other element your dragged element was dropped just through some coordinate adding and subtracting. To find an arbitrary drop point, you'll have no other cross-browser recourse but to examine the page positions of all possible targets so see if they contain the coordinates of the mouse cursor during the mouseup event. Complicated, but definitely not impossible if you're determined.

Hopefully this script framework helps you get a head start on custom drag and drop functions. Good luck!


Comments closed

Recent posts

  1. Customize Clipboard Content on Copy: Caveats Dec 2023
  2. Orcinus Site Search now available on Github Apr 2023
  3. Looking for Orca Search 3.0 Beta Testers! Apr 2023
  4. Simple Wheel / Tire Size Calculator Feb 2023
  5. Dr. Presto - Now with MUSIC! Jan 2023
  6. Archive