Download drag'n drop folder tree

Demo

Bookmark and Share

Licensing

This script is distributed under the LGPL open source license.
Commercial licenses are also available. Some of these licenses also includes personal e-mail support for up to 1 year.

Download files

You can download the entire script from this Zip file.

Files included in the package:

  • drag-drop-folder-tree.html = Main html file
  • js/drag-drop-folder-tree.js = Main Javascript file
  • js/context-menu.js = JS code for the context menu
  • js/ajax.js = Ajax (Library from http://twilightuniverse.com/projects/sack). Used for the save method.
  • saveNodes.php = Saving nodes. You need to configure this file, i.e. database connection and query.
  • folderTree_updateItem.php = Rename or delete an item on the server. This file is called by ajax.
  • images/* = Images used by the script
  • css/drag-drop-folder-tree.css = CSS file used by the script
  • css/context-menu.css = CSS file used by the context-menu

Configuration

Define the tree

The tree is created by a standard <UL><LI> list as in drag-drop-foler-tree.html.

Notice that you have three attributes available which you could assign to your <LI> tags.

  • noDrag - If you set this to "true", it means that this list item won't be dragable.
  • noChildren - When this attribute is set to true, it won't be possible to move items to this node.
  • noSiblings = It is not possible to add items above or below this node, only children.(This is an attribute you typically use only on a root node).
  • noDelete = It is not possible to delete this node.
  • noRename = It is not possible to rename this node.

Creating tree object

Below the HTML of your tree, you create a tree object like this:

<script type="text/javascript">
treeObj = new JSDragDropTree();
treeObj.setTreeId('dhtmlgoodies_tree2');
treeObj.setMaximumDepth(5);
treeObj.setMessageMaximumDepthReached('Maximum depth reached');
treeObj.initTree();
</script>

First, you create the tree object, then you define the id of your tree, i.e. the id of the top <UL>(example: <ul id="dhtmlgoodies_tree2"...).

The following methods until initTree() are optional. See description of available methods below.

Methods

the JSDragDropTree class has the following methods:

  • setMaximumDepth = Setting maximum depth of tree. Dropping of nodes would be cancelled automatically if the depth exceeds this number. Instead it would move the dragged nodes back to it's original location. Default value is 6.
  • setMessageMaximumDepthReached = Message to the user when he drop nodes and depth exceeds defined maximum depth.
  • setImageFolder = Specify path to images. Default is "images/".
  • setFolderImage = Specify name of folder image, example: "dhtmlgoodies_folder.gif"
  • setPlusImage = Specify name of small [+] image
  • setMinusImage = Specify name of small [-] image
  • setTreeId = Specify id of tree
  • expandAll = Expand all nodes - must be called after initTree()
  • collapseAll = Collapse all nodes - must be called after initTree()
  • getNodeOrders = Returns the order of the nodes in the tree in the format id-parentID,id-parentID,id-parentID
  • setFileNameRename = Specify name of file to call after a node has been renamed. Variables to this file will be "renameId" and "newName". Default file is "folderTree_updateItem.php"
  • setFileNameDelete = Specify name of file to call after a node has been deleted. Variables to this file will be "deleteIds" which is a commaseparated list of ids for the deleted nodes. Default file is "folderTree_updateItem.php"
  • setRenameAllowed = Enable or disable rename of nodes. This variable is default set to true. Set it to false if you don't want to allow any nodes to be renamed.
  • setDeleteAllowed = Specify if it's possible to delete nodes in the tree. This variable is default set to true. Set it to false if you don't want to allow any nodes to be deleted.
  • additionalRenameRequestParameters = Add parameters sent to the Ajax rename request. Argument to this methods should be an associative array. Example:
    tree.setAdditionalRenameRequestParameters({
    name: "treeAction",
    command: "renameNode"
    });

    which will add the variables name and command to the request sent to the server when an item is being renamed.

  • setAdditionalDeleteRequestParameters = Add parameters sent to the Ajax delete request. Argument to this methods should be an associative array. Example:
    tree.setAdditionalRenameRequestParameters({
    name: "treeAction",
    command: "deleteNode"
    });

    which will add the variables name and command to the request sent to the server when an item is being deleted.

Save a tree

When you want to save the changes you made, you need to create your own save function. Here's an example how it is done in the demo(drag-drop-folder-tree.html):

//--------------------------------
// Save functions
//--------------------------------
var ajaxObjects = new Array();

function saveMyTree()
{
    saveString = treeObj.getNodeOrders();
    var ajaxIndex = ajaxObjects.length;
    ajaxObjects[ajaxIndex] = new sack();
    var url = 'saveNodes.php?saveString=' + saveString;
    ajaxObjects[ajaxIndex].requestFile = url;  // Specifying which file to get
    ajaxObjects[ajaxIndex].onCompletion = function() { saveComplete(ajaxIndex); } ;  // Specify function that will be executed after file has been found
    ajaxObjects[ajaxIndex].runAJAX();    // Execute AJAX function      
  
}
function saveComplete(index)
{
  alert(ajaxObjects[index].response);  
  
}

This will send the nodes to the server by use of Ajax.

You may also use a plain form when you submit the data. Then the saveMyTree function could look something like this:

function saveMyTree_byForm()
{
  document.myForm.elements['saveString'].value = treeObj.getNodeOrders();
  document.myForm.submit();    
}

Update log

  • Nov, 10th, 2006: Added delete and rename features

Comments

Tutozed
Great script! is there a way to save automaticly after dragging the folder. Without submit button?
Tutozed at 05:06PM, 2011/04/06.
Tutozed
Nevermind i figured out!

on line:364 in drag-dop-folder-tree.js
(after moveDragableNodes : function(e)
{ )

past this:

saveString = JSTreeObj.getNodeOrders();
var ajaxIndex = JSTreeObj.ajaxObjects.length;
JSTreeObj.ajaxObjects[ajaxIndex] = new sack();
var url = 'saveNodes.php?saveString=' + saveString;
JSTreeObj.ajaxObjects[ajaxIndex].requestFile = url; // Specifying which file to get
JSTreeObj.ajaxObjects[ajaxIndex].onCompletion = function() { JSTreeObj.saveComplete(ajaxIndex,obj); } ; // Specify function that will be executed after file has been found
JSTreeObj.ajaxObjects[ajaxIndex].runAJAX(); // Execute AJAX function
Tutozed at 05:21PM, 2011/04/06.
Anthony
excellent, although how do you make to active? the downloaded file appears to have saving deactivated like the demo..
Anthony at 03:28PM, 2011/04/20.
Dany
To save in PHP, make sure the php files start with a <?php tag. the "php" part in "<?" in the file is missing.

so from "<? ...file content... ?>"
to "<?php ...file content... ?>"
Dany at 02:12AM, 2011/04/27.
murray
I love this!!
Only thing I'd add is a create new child item on the menu.
many thanks
murray at 09:34AM, 2011/05/30.
Suraj Chandran
hi,
I have one doubt.
when i try to get the node orders.
i get the id orders but the orders will have only numeric contents.
i trying to retrieve the data through asp.net
regards,
suraj
Suraj Chandran at 05:06AM, 2011/06/22.
Eric Chang
This is a excellent script ! But How can I save my own order ?
Eric Chang at 01:56AM, 2011/07/12.
Eric Chang
I try to modify this line in savemytree function to my own asp file
var url = 'http://adfs.pic.com.tw/mtree/saveNodes.asp?saveString=' + saveString;
and this is my asp file
<html>
<head>
<title>Test String</title>
</head>
<body>
<%
st = Request.QueryString("saveString")
Response.Write saveString
%>
</body>
</html>
But I only get this messages
http://adfs.pic.com.tw/dragdropmenu-01.jpg
How can I fix the problem ?
Eric Chang at 02:52AM, 2011/07/12.
Eric Chang
sorry , it`s me again = =
I find one error in my asp file
this new asp file.
<html>
<head>
<title>Test String</title>
</head>
<body>
<%
st = Request.QueryString("saveString")
Response.Write st
%>
</body>
</html>
But I only get a string like
http://adfs.pic.com.tw/dragdropmenu-02.jpg
How can I make the order effected with new one ?
Eric Chang at 02:58AM, 2011/07/12.
Yoni
The string now is like this:
10-0, 11-10, 12-10, 1-0, 2-0, 3-2

is it possible to have ther ordered number as well like this?
10-0-0, 11-10-0, 12-10-1, 1-0-1, 2-0-2, 3-2-0
Yoni at 03:22AM, 2011/07/30.
Pieterjan Criel
Great script, Thx

I didn't find any code to generate the list's in this zip. (maybe I didn't search very good)

I wrote this to make an auto-list-tree based on the information in the database. It's not very "good" but it works. (I didn't add any of the possible options because I didn't need them)

function makeUnnumberedList($a){

$result = mysql_query("SELECT * FROM nodes WHERE parentID=$a");

if(mysql_num_rows($result) == 0)
{
// nothing
}
else
{
echo "<ul>";
}

while($row = mysql_fetch_array($result))
{
echo '<li id="node'.$row['ID'].'">'.'<a href=#>'.$row['title'].'</a>';
makeUnnumberedList($row['ID']);
echo '</li>';
}
if(mysql_num_rows($result) == 0)
{
// nothing
}
else
{
echo "</ul>";
}

}
Pieterjan Criel at 10:54AM, 2011/08/05.
Alta
I love this!
I need it to accept nodes with alpha as well as numbers. It seems to strip out the alpha.
Alta at 10:19AM, 2011/08/15.
Alta
I got it! To be able to use alpha, id your li elements with
"node" as the prefix. Include your own code just after the node.

Then, in drag-drop-folder-tree.js, just after

,getNodeOrders : function(initObj,saveString) {

change
var numericID = li.id.replace(/[^0-9]/gi,'');
to
var numericID = li.id.replace(/node/,'');

And, right after that, change
var numericParentID = li.parentNode.parentNode.id.replace(/[^0-9]/gi,'');
to
var numericParentID = li.parentNode.parentNode.id.replace(/node/gi,'');

Very nice :)

p.s. I needed this because my database sorts the tree as follows:
1
.11
.12
..121
..122

2
.21
.22

3
.31
..311
..312

etc. When the sibling nodes go past 9, they then use the alpha,
'a', 'b', etc.

THANK YOU for such a great code!
Alta at 05:34PM, 2011/08/15.
RK
I need to block some folders should not allow dragging into it. is that possible?
RK at 06:20AM, 2011/08/31.
RK
I need to block the folders to dragging in to it. Is that possible?
RK at 06:21AM, 2011/08/31.
Ryan
Can I populate the nodes from a web glassfish webservice response? If so, how would i do that?
Ryan at 07:05AM, 2011/11/21.
danix
I have a problem.
When i put the <ul> tree in a div of master.page the script have same problem
danix at 01:06AM, 2011/12/03.
Sjoerd
@RK: Yes that's possible. Use the 'noChildren' class.
------------
@Danix: Say what?!
------------

I got another question:
Is it possible when you reach the maximum depth, to place the items on the max level? (Now it gives a message 'maximum depth reached'..

Thankyou for the answer!
Sjoerd at 06:21AM, 2011/12/22.
Johan
Yeah! It is a really good script.

But, I have found one thing that does not work that well.

If you set a node to "no children", you cant drag other nodes as childs. OK
But if the "no children"-node already has childrens you can add the moving node as a sibling to the existing childrens.

I have tried to fix this in "moveDragableNodes" (see main js-file). But I have failed.

So anyone that have an idea?
Thanks /Johan
Johan at 08:58AM, 2012/02/03.
Johan
@ Sjoerd: Do you want a level-limit? One way could be to set max.depthlevel as you wish "plus one"? Or maybe I dont missunderstand? =)

/Johan
Johan at 09:01AM, 2012/02/03.
Michael Mofokeng
I have a table with 2 columns, 1 column I added drag-drop and the other just plain html but the drag-drop control is rendering outside (on top of the containing table) the table column. How can I fix this issue?
Michael Mofokeng at 04:22AM, 2012/03/14.
Andrei
Great tree menu, easy to use.

I have a question, is possible expand the menu when click on name folder, not plus?
Thanks.
Andrew
Andrei at 02:38AM, 2012/03/21.
Admin comment
DHTMLGoodies
Hei Andrew,

Add

this.addEvent(aTag, 'click', this.showHideNode);

on line 796, just below

aTag.id = 'nodeATag' + menuItems[no].id.replace(/[^0-9]/gi,'');

I think that should do the trick. I have updated the demo and the zip file with this fix.
DHTMLGoodies at 02:30PM, 2012/03/21.
Rado
Hello,
the script is great, but can you please let me know if is there also a possibility to place on the same page two or more independent trees with the drag-drop funcionality?

Each of the trees on the page would have its own parents and chindren and the dragged children of the focused tree will be possible to save in the DB.

If yes, plese give me a hint how to do it.

Thanks in advance for your support
Rado

Rado at 02:53PM, 2012/03/30.
Cleiton Silva Barbosa
Lacked the "order" to be correct.


<a href="#comment799">Pieterjan Criel wrote:</a>
Great script, Thx

I didn't find any code to generate the list's in this zip. (maybe I didn't search very good)

I wrote this to make an auto-list-tree based on the information in the database. It's not very "good" but it works. (I didn't add any of the possible options because I didn't need them)

function makeUnnumberedList($a){

$result = mysql_query("SELECT * FROM nodes WHERE parentID=$a");

if(mysql_num_rows($result) == 0)
{
// nothing
}
else
{
echo "<ul>";
}

while($row = mysql_fetch_array($result))
{
echo '<li id="node'.$row['ID'].'">'.'<a href=#>'.$row['title'].'</a>';
makeUnnumberedList($row['ID']);
echo '</li>';
}
if(mysql_num_rows($result) == 0)
{
// nothing
}
else
{
echo "</ul>";
}

}


Cleiton Silva Barbosa at 12:51PM, 2012/05/05.
matjaz
Hi

Is it possible to add the ADD function same as DELETE and REMOVE. Would really apprecaite it.

Thanks
matjaz at 02:56PM, 2012/05/21.
Janos
How can I rename the folders? It doesnt send the names only the position... :-(

And how can I add new folder? :-)
Janos at 07:56AM, 2012/05/29.
swati
how to add element in this tree & delete an item from tree
swati at 03:35AM, 2012/06/15.
snssuf
it's very good
snssuf at 10:00PM, 2012/06/17.
snssuf
it's ok
snssuf at 10:01PM, 2012/06/17.
swati
Delete menu is not working,
onError returns my message to me too. the php file and the html file are in the root directory and the js file is in the subdirectory of js.
still m not able to delete the node.
can anyone help me?..........
swati at 04:55AM, 2012/06/18.
Kevin
Is there a way to select multiple folders to drag? For example if you hold down shift and select a couple of folders that you would like to drag.
Kevin at 09:04AM, 2012/06/26.
Mark
Really good script.
I hope someone can give me a quick answer for this :-).
I have two trees and i can drag across fine and everything works perfect. My only snag is I would like my first tree to remain a static list so i can pull over the same node more than once but as soon as I drag the node over its removed from the first tree.

Any ideas how I can stop this?

Mark
Mark at 09:06AM, 2012/07/05.
Dax
I'm using ajax to replace the contents of an <li></li>, is there a way to init just these contents after they are replaced?
Dax at 11:58PM, 2013/01/03.
John
Has anyone modified script to add nodes or files to the tree?
John at 09:24AM, 2013/01/09.
Amandeep Singh
Very nice script,

but when i tried to add Root node in side the <div> tag then i am getting the Root node in nect line.
i tried adding table but got the same result its like
i doing changes in .html file.

<li id="node0" noDrag="true" noSiblings="true" noDelete="true" noRename="true"><a href="#"><div><table><tr><td>Root node</td></tr></table></div></a>

i am getting the Root ode in next line.


Please suggest/add some snippet to add <div><table> tag
Amandeep Singh at 06:16AM, 2013/02/27.
fahad
The script which i was looking for.Easy to use and embed.
But the demo I downloaded is <strong>not deleting the nodes even though it shows the confirmation box too</strong>.Could any one plzz help me to figure out the problem.
fahad at 10:55PM, 2013/06/17.
Stanley
Hi
How can i remove remove <li id="node0" noDrag="true" noSiblings="true" noDelete="true" noRename="true"><a href="#"></a>
this code and the other can't appear error ?
thx

you so cool!
Stanley at 04:23AM, 2014/01/22.
PHAMDUYVT
thanks, greate script
PHAMDUYVT at 05:43PM, 2014/03/05.
Sayed
How can we drop a file from computer and added in any folder of this tree structure????
Sayed at 01:06PM, 2014/05/19.
Caglar ORHAN
For any one needs as me. To save automatically after drop;
1) Create a function includes all saving futures and other function calls. (my function name is saveImm).
2) In drag-drop-folder-tree.js file just after 482. row and before closing drop function called dropDragableNodes:function(). Add your saving function call.

my function call is:
saveImm();
also 480-484 look like this:
480:JSTreeObj.dropTargetIndicator.style.display='none';
481: JSTreeObj.dragDropTimer = -1;
482: if(showMessage && JSTreeObj.messageMaximumDepthReached)alert(JSTreeObj.messageMaximumDepthReached);
483: saveImm();
484: }
Caglar ORHAN at 10:30PM, 2014/05/22.
jb
Wow looks nice. Adding an open folder icon (after expansion) would put it over the top! :)
jb at 01:23PM, 2014/06/20.
Bill
I have made progress in applying drag-drop-folder-tree in production. I can create the html list from a MySQL db, and drag & drop correctly updates the db.

I can also successfully update my db when renaming a node and/or deleting a node. However, I am getting an error alert for both operations, even though they both work correctly.

The alerts appear to be generated in drag-drop-folder-tree.js, lines 632 and 645. Does anyone know why the alerts are generated and how to prevent them unless there truly is an error? I do not know javascript nor ajax, so I have no idea how to fix this.

Thanks
Bill at 09:27AM, 2014/08/16.

Post your comment

Don't have an avatar? Create one at Gravatar.com.

Confirmation code:

Go to cbolson.com


About/Contact | A good idea? | Submit a script | Privacy notice
© 2005 - 2014 dhtmlgoodies.com