16/07/08 UPDATE: A new beta version is now available with some bug corrections. Thanks to Randy for the useful feedback!

29/06/08 UPDATE: Handler feature added! Finally I decided to add a little piece of extra functionality to the EasyDrag plugin. It has been constantly requested, so now you can download and test it. I will be releasing it as a final version after some feedback, so please let me know if it works for you.

How does it work?

It’s very simple, first you call the easydrag() method as in the old version and then you call the setHandler() method passing to it the id of the element that will act as the handle. The handle MUST be a child element of the content that will be dragged.

$("#box2").easydrag();
$("#box2").setHandler('handler3');

Files

jquery.easydrag.handler.beta2.js

It has been a while since my last post, mainly because I’m currently a little busy with some projects. In one of these projects I had to add a drag-and-drop behavior to some DOM elements, and for that I have created the EasyDrag jQuery plug-in that I’ll share with you now.

Its main purpose is to add the ability to drag and drop almost any DOM element without much effort. So it’s simple to use and you can also attach handlers both to the drag and to the drop events, which permits you to extend the basic functionality to whatever you need.

How to use

To be able to use this plugin you should set the element you want to drag as absolute positioned and set an unique id for it (although it’s not strictly necessary because the script will try to set both for use otherwise). You are also advised to set the size of the element. Finally you need to add a code similar to the following example into your page.

<script src="jquery.easydrag.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
	// add drag and drop functionality to #box1
	$("#box1").easydrag();
 
        // set a function to be called on a drop event
	$("#box1").ondrop(function(e, element){ alert(element + " Dropped"); });
});
</script>

It’s the #box1 of the above example. Try dragging it and watch the alert when you drop it.

Events

You can attach a function to be called when an element is being dragged and also another function to be called when the element is dropped passing them as a parameter to .ondrag and to .ondrop functions of the plugin. The plugin will pass an event object and the current element as the parameter to the attached functions.

Event Bubbling

By default EasyDrag is set to stop event bubbling so you can drag a div around without any problem but if you have elements inside a div, like a form for instance, you need to enable event bubbling to be able to interact with them.

To enable event bubbling simply pass “true” to the easydrag function as in the following example:

$("#box1").easydrag(true);

Control

You can use the methods .dragOff() and .dragOn() to disable and enable the dragging behavior respectively.

Files

jquery.easydrag.js