I recently had a need for a YUI (Yahoo! User Interface) TreeView with Drag & Drop nodes. Here's a little background on the project. My web application uses YUI Menu for navigation and is driven by a single database table. Initially I threw together a quick and dirty CGI CRUD interface to manage the menu. But, the more I had to modify the menu with this interface the more I needed something easier to use. So I decided to scrap the CGI interface and start over with a nice 100% Ajax interface with a YUI TreeView to represent the YUI Menu. Adding, changing, and deleting nodes is pretty easy, but to easily change the order of the Menu items, I added YUI Drag & Drop to the TreeView.
The example I created is essentially a merge of two YUI examples with some tweaks. The base code I used for this example is the Default TreeView example. For my web app, the TreeView is dynamically loaded. Either way, drag and drop will work. The Reordering a list example was the best fit for my needs so it is used for drag and drop.
Here is the onDragOver function with tweaks to allow for dragging a nested node over it's parent without too much quirkiness:
onDragOver: function(e, id) {
var srcEl = this.getEl();
var destEl = Dom.get(id);
// We are only concerned with menu items, we ignore the dragover
// notifications for anything else.
if (destEl.id.match(/^ygtv[0-9]+$/)) {
var orig_p = srcEl.parentNode;
var p = destEl.parentNode;
var destIdx = destEl.id.match(/[0-9]+$/);
var destTreeNode = oTextNodeMap['ygtvlabelel' + destIdx];
// Ignore any parent that is expanded
// If !expanded
if (! destTreeNode.expanded) {
if (this.goingUp) {
p.insertBefore(srcEl, destEl); // insert above
lastDestId = destEl.id;
}
else {
p.insertBefore(srcEl, destEl.nextSibling); // insert below
lastDestId = destEl.id;
}
}
DDM.refreshCache();
}
}
The finished example of the TreeView with Drag & Drop:
