Quick and dirty jQuery drag & drop

Categories

Tags

I feel kinda bad to be calling this dirty, but mind you, I’m only using dirty as an expression, as it’s freaking sweet.

In fact, I’ve been having a few ideas about using drag & drop for an open source application I’ve been thinking of, and decided to play with jQuery UI to do that.

The fine guys at Packt have recently sent me a jQuery UI 1.6 book and I’ve been able to come up with this

It’s a pretty simple example I know, but it took me only a few minutes to come up with it. if you come from the old-school javascript times, you know that it would take you hours, if not days to develop something similar, and you’d still have all the hassle of testing it in multiple browsers.

I’ll try to explain what my code does here, but the comments pretty much say everything.

And now it’s time for the magic to happen. All the functionality will be on the following lines, and the comments pretty much say everything that’s being done:

<scripttype="text/javascript"><!--$(document).ready(function(){//Create a callback function for when the object is dropped into the areafunctioneventCallBack(e){alert('dropped')}//Dragging propsvardragOpts={revert:true,cursor:"move"};//Dropping propsvardropOpts={activeClass:"activated",drop:eventCallBack}//Make element draggable$("#drag").draggable(dragOpts);//Make element droppable$("#target").droppable(dropOpts);});// --></script>

Finally I create the object I’m gonna be dragging, and a container to “receive” my object, so the drag & drop will only return a call-back when the object is dropped inside my target

<div id="drag">Drag</div>

And that’s all I have to do to have a fully functional drag & drop using jQuery