Drag – Drop Interaction with jQuery
A few days ago, I posted about getting started with AJAX, Facebox and jQuery. Well, I've been doing a little more work with it, and wanted to do a quick demo of the Drag and Drop interaction that is possible with jQuery, and a little preview of how to deal with this stuff and AJAX. It's pretty slick.
First of all, go and get the jQuery library, the jQuery UI library. Add script tags that point to the jQuery Library, and then the ui.draggable.js, ui.draggable.ext.js, ui.droppable.js, ui.droppable.ext.js, and ui.mouse.js files from the jQuery UI library.
Then, drop two divs on a page. Give them two different id's.
<!DOCTYPE
html
PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Untitled Page</title>
<script
src="../JS/jquery-1.2.2.pack.js"></script>
<script
type="text/javascript"
src="../JS/jquery.ui-1.0/ui.mouse.js"></script>
<script
type="text/javascript"
src="../JS/jquery.ui-1.0/ui.draggable.js"></script>
<script
type="text/javascript"
src="../JS/jquery.ui-1.0/ui.draggable.ext.js"></script>
<script
type="text/javascript"
src="../JS/jquery.ui-1.0/ui.droppable.js"></script>
<script
type="text/javascript"
src="../JS/jquery.ui-1.0/ui.droppable.ext.js"></script>
<style>
#divDrop
{
margin-left:auto;
width:250px;
height:250px;
background-color:powderBlue;
}
#divDrag
{
width:100px;
height:100px;
position:absolute;
top:0px;
left:0px;
background-color:yellow;
}
.droppable-active {
opacity: 1.0;
background-color:yellow;
}
.droppable-hover {
outline: 1px
dotted
black;
background-color:white;
}
</style>
<script>
$(document).ready
(
function()
{
$("#divDrag").draggable({helper: 'clone'});
$("#divDrop").droppable({
accept: "#divDrag",
activeClass: 'droppable-active',
hoverClass: 'droppable-hover',
drop: function(ev, ui) {
$(this).append("<br>Dropped!");
var theId = $(this).attr("id");
alert(theId);
//Do your AJAX stuff in here.
}
});
}
);
</script>
</head>
<body>
<div
id='divDrop'>Drop Here.</div>
<div
id='divDrag'>Drag Me.</div>
</body>
</html>
That's the gist of it. As you can see, the possibilities now are endless. What's really impressive is drag and drop in well, as little as two lines of code.
Enjoy!