jQuery File Tree

A configurable, AJAX file browser plugin for jQuery.

Contents

  1. Overview
  2. Features
  3. Compatibility
  4. Demo
  5. Download
  6. Usage
    1. Dependencies
    2. Creating a File Tree
    3. Configuring the File Tree
    4. Styling the File Tree
    5. Handling Feedback
  7. Connector Scripts
    1. Custom Connector Scripts
  8. Version History
  9. Licensing & Terms of Use
  10. Special Thanks
  11. Comments

Overview

jQuery File Tree is a configurable, AJAX file browser plugin for jQuery. You can create a customized, fully-interactive file tree with as little as one line of JavaScript code.

Currently, server-side connector scripts are available for PHP, ASP, ASP.NET, JSP, and Lasso. If you’re a developer, you can easily make your own connector to work with your language of choice.

Features

Compatibility

jQuery File Tree requires jQuery 1.2.6 or above and has been tested to work in the following browsers:

Demo

View a live demonstration of the file tree with various options.

Download

Current version: Version 1.01 (12 April 2008)

This plugin is provided to you as-is, at absolutely no cost. If you would like to support its development, feel free to contribute any amount you prefer via PayPal. As always, you are welcome to contribute code for bug fixes and feature enhancements as well. Either way, thanks for supporting our efforts!

Usage

Dependencies

jQuery File Tree requires jQuery 1.2 or above. For easing effects, you will need the jQuery Easing Plugin or another jQuery easing plugin of your choice.

Creating a File Tree

In it’s simplest form, you can create a file tree using the following code:

$(document).ready( function() {
    $('#container_id').fileTree({ root: '/some/folder/' }, function(file) {
        alert(file);
    });
});

where #container_id is the ID of an empty DIV element that exists on your page. The file tree will automatically load when your page loads.

Configuring the File Tree

Parameters are passed as an object to the fileTree() function. Valid options include:

ParameterDescriptionDefault Value
rootroot folder to display/
scriptlocation of the serverside AJAX file to usejqueryFileTree.php
folderEventevent to trigger expand/collapseclick
expandSpeedSpeed at which to expand branches (in milliseconds); use -1 for no animation500
collapseSpeedSpeed at which to collapse branches (in milliseconds); use -1 for no animation500
expandEasingEasing function to use on expandNone
collapseEasingEasing function to use on collapseNone
multiFolderWhether or not to limit the browser to one subfolder at a timetrue
loadMessageMessage to display while initial tree loads (can be HTML)Loading...

To create a file tree with multiple parameters, your code will look something like this:

$(document).ready( function() {
    $('#container_id').fileTree({
      root: '/some/folder/',
      script: 'jqueryFileTree.asp',
      expandSpeed: 1000,
      collapseSpeed: 1000,
      multiFolder: false
    }, function(file) {
        alert(file);
    });
});

Styling the File Tree

The file tree relies 100% on CSS for styling. To give your users an aesthetically pleasing experience, you should either use the included stylesheet for your file tree or create your own. Refer to jqueryFileTree.css to make any changes in the styles.

Handling Feedback

When a file is selected, jQuery File Tree passes the filename back as a string. The easiest way to capture and handle this is by using an anonymous function. If you want to pass the selected filename to a function you create called openFile(), your code will look like this:

function openFile(file) {
    // do something with file
}

$(document).ready( function() {
    $('#container_id').fileTree({ [options] }, function(file) {
        openFile(file);
    });
});

Connector Scripts

jQuery File Tree comes with a handful of serverside connector scripts that are used to read the file system on your server and return data to the clientside script via AJAX. The default connector script is jqueryFileTree.php. You can use a connector script for another language by setting the script parameter to the location of the script you want to use (see Configuring the File Tree). Alternatively, you can build a custom connector script to extend the functionality of jQuery File Tree to better suit your needs (see Custom Connector Scripts).

Connector scripts for the following languages are included in the download:

If you would like to share a connector that you’ve written for another language, let us know! We’ll be happy to add it to the download for everyone to use!

The connector scripts provided with jQuery File Tree are only designed to read information from a specified root folder. Although this is typically harmless, there exists a potential for malicious individuals to be able to view your entire directory structure by spoofing the root parameter. It is highly recommended that you add some form of check to your connector script to verify the path being scanned is a path that you want to allow visitors to see.

Custom Connector Scripts

You can create a custom connector script to extend the functionality of the file tree. The easiest way to do this is probably by modifying one of the scripts supplied in the download. If you want to start from scratch, your script should accept one POST variable (dir) and output an unsorted list in the following format:

<ul class="jqueryFileTree" style="display: none;">
    <li class="directory collapsed"><a href="#" rel="/this/folder/">Folder Name</a></li>
    (additional folders here)
    <li class="file ext_txt"><a href="#" rel="/this/folder/filename.txt">filename.txt</a></li>
    (additional files here)
</ul>

Note that the corresponding file extension should be written as a class of the li element, prefixed with ext_. (The prefix is used to prevent invalid class names for file extensions that begin with non-alpha characters.)

Version History

1.01

1.00

Licensing & Terms of Use

This plugin is dual-licensed under the GNU General Public License and the MIT License and is copyright 2008 A Beautiful Site, LLC.

Special Thanks

A special thanks goes out to FAMFAMFAM for their excellent Silk Icon Set.

Comments

Looks really great! Nice job.

Any plans for jpg thumbnail support?

Floopie on Mar 26th, 2008

very well designed and cute

Coskun on Mar 27th, 2008

Any plans to offer a JSP connector?

Demetrios Kyriakis on Mar 27th, 2008

Demetrios, I'd love to offer more connectors including JSP, ColdFusion, Ruby, etc. If you or anyone else is willing to write a stable connector for another language I will be glad to include it (with credit, of course) in the download.

Cory S.N. LaViska on Mar 27th, 2008

I think that's a very nice plugin. Thanks for creating it with customization and flexibility in mind. That's what I always need when using plugins. Great job.

Ihsan on Mar 27th, 2008

Congrats ! This plugin is just great..
Just one thing,.. when I change the handler to openFile(file) and click on a file in the tree, nothing happens ? Did I forget something ?

John on Mar 28th, 2008

John, I've updated the article to better explain this. Please reread the section on Handling Feedback.

Cory S.N. LaViska on Mar 28th, 2008

openFile(); method isn't part of the package. It's just an example of how you can use an anonymous callback function.

Levi Lewis on Mar 28th, 2008

Thanks for the feedback guys,... you might also point out the scandir() function in jqueryFileTree.php is only supported in PHP5 (yet alternative methods are available in PHP4)

John on Mar 28th, 2008

Good call, John. I've posted a PHP4 alternative to scandir() here: http://abeautifulsite.net/notebook.php?article=59

Cory S.N. LaViska on Mar 28th, 2008

I am already using jQuery. This plug-in looks cool in demo. I love to use it in future projects.

Kevin on Mar 28th, 2008

Excellent, just need a bit modifications to fit what i need, a checkbox to get multiselect file name for further process

thank you

bali web designer on Apr 1st, 2008

Very nice work!

Seeing some great uses for this project, yet just not right now. Would be neat to see some features like (yes, these are Ext/YUI inspired):

- get data from a JSON/XML file, and no output in pure UL's (and not necessarily link it to a filesystem)
* bonus: load in the tree in one call

- drag and drop support
* treenode properties such as: allowChildren, allowDrag, etc.

- save tree state in cookie

- some functions like:
* get a node and manipulate it (change text or icon for example)
* reload the tree
* collapse the full tree
* ..

Just sending in some suggestions here, maybe they'll make in the 2.0 release. If you need any help on these here, feel free to ping/mail me ;)

Bramus! on Apr 1st, 2008

Congratulations for your beautiful work!
I found it very useful, and since I am currently working with the prototype framework, I picked your plugin and translated it for prototype.

You can find it on my website (I gave you all the credits you need :) )

Oh, I fused the PHP4 scandir "hack" into the PHP connector ...

Please, pay a visit and tell me what you think, we could even enlarge our projects and work together to make them better and better.

My regards ! ;)

Daniele Di Bernardo on Apr 1st, 2008

Superb script! I`d like to translate this article to Polish.

regards

decimus on Apr 1st, 2008

Pretty amazing. I could definitely this.

mark on Apr 1st, 2008

Forgot to tell you the reference page for my Prototype File Tree project:

http://www.marzapower.com/blog/show/211

Daniele Di Bernardo on Apr 2nd, 2008

The best solution for my problem!

pavlentij on Apr 4th, 2008

please help me!! jquery file tree dont work for spanish directories. E.g.: c:\imágenes.
please mail me!!!
thnx!!!

Ignacio on Apr 11th, 2008

Ignacio, I have updated the script to work with foreign characters. Please download the latest version.

Cory S.N. LaViska on Apr 12th, 2008

Excelent! Thanks for update!! :)

Ignacio on Apr 14th, 2008

very nice work, how to expand all the folder when the page loaded.

Prakaash on Apr 18th, 2008

Hello everybody, in 1st place i would like to thank Cory for this script.

Now ... can please anyone tellme how to make the files downloadble? Make an example/ piece of code for dummies like me :)

tanks in advance for your time

Luis

Luis on Apr 19th, 2008

Awesome script! Does anyone have any ideas how you could programatically drill-down into nested folders? I know I can trigger the click event on single directories, but I'd like to drill-down several directories deep. I can't seem to work out a solution to this.

Travis Phipps on Apr 21st, 2008

FYI: Looks like the zip archive linked on this page still contains v1.0 of the plugin. I was able to get v1.01 from the demonstration site.

Travis Phipps on Apr 22nd, 2008

Thanks, Travis. I've corrected the download now. It reverted last night when I added the JSP connector.

Cory S.N. LaViska on Apr 22nd, 2008

tanks alot for the file tree. i have modified it to be used as a navigation for my portfolio site: http://www.kasparbumke.net
some questions:
1.how should i credit your work?
2. is it possible to make the hyperlink for folders actually go somewhere. (i want the page in another frame to change) ?
3. Any way to include the icons in the hyperlink?

just point me to where in the files this could be changed and i will figure it out.

kaspar on Apr 22nd, 2008

I was finally able to programmatically navigate the tree structure! I had to add an "ajaxCallback" to the plugin to support what I needed. I simply added the following line: if( o.ajaxCallback != undefined ) o.ajaxCallback(t);
after the bindTree(c) function call. This allows me to specify a function to be called after each AJAX call. Then I can use this to navigate down into a specific sub-folder n levels deep. Thanks again for such a great control!

Travis Phipps on Apr 23rd, 2008

I cannot use it. I added all the files in the same directory, I uploaded them but it shows me a blank file tree. Though, the Connector works. When I access the website, it loads everything (Loading...) but the tree is not visible. In DOM I can only see the original node. Can you help me with that?

Sabrina on Apr 24th, 2008

The JSP Backend contains a small bug:
In the extension exatraction line:
String ext = dotIndex > 0 ? file.substring(dotIndex) : "";
there should be used "dotIndex + 1" to get the correct extension without the dot.

Demetrios Kyriakis on May 1st, 2008

Any plans to add some more functionality to your file tree?
E.g. something like the FileTree from ExtJS project?
http://filetree.extjs.eu/

The backend protocol might be described in the link above could be used for your tree too since it supports all required operations.

Demetrios Kyriakis on May 1st, 2008

I am not able to get it to work. I just see empty div. Could you also include the code for the demo page in the zip file as well. Thanks.

adarsh on May 3rd, 2008

This was almost exactly what I was looking for, simple and not over bloated with a million features I won't use. There is one thing I need to be able to do, any suggestions or pointers would be greatly appreciated.
I'm calling the initial function several times in a page, but I need to be able to "title" each dir listing. I hope that makes some sort of sense.
Thanks.

Stephen on May 7th, 2008

use
HttpUtility.UrlDecode(Request.Form["dir"])

in C# for better location

Ernest on May 7th, 2008

Ok, I figured it out - well, I figured out something that would work for me.
Fist of all, add a variable to pass to jqueryFileTree.js (I used base:)

$(document).ready( function() {
$('#dirList').fileTree({ root: 'USVDR11/', script: 'jqueryFileTree.php', multiFolder: false, base: 'Service Desk' }, function(file) {
showFile(file);
});
});

and then, in the connector (jqueryFileTree.php in my case) just before the echo"<ul..."; add

echo "<div id=\"base\" style=\"display: none;\"></div>";

and lastly in the jqueryFileTree.js add the following to the list of "defaults":
if( o.base == undefined ) o.base = 'Tree';

and lastly add
$(c).find('DIV:hidden').replaceWith(o.base).show();
to the beginning of the if statement in the show() function.

This may not be the best or most clever way to handle it, but it works for me.

Thanks.

Stephen on May 9th, 2008

Sorry - at the end, that should have been showTree() function

Stephen on May 9th, 2008

I'm going to have to say that I'm a little disappointed that there's not drag-drop support built in. Ext JS's platform has this support, but their library is a massive honking multi-megabyte download. jQuery is much nicer. If you could add drag-drop support, I would pay you to use the tree in my apps.

Matt on May 10th, 2008

Int he multi-param example you have a ";" as a terminator after the word "false". That is a syntax error, just drop it :)

Soulhuntre on May 14th, 2008

Hi, when I creating nonjavascript link (example: filetree.php?module=files&file=image.jpg) for file in the directory, and I click on this link in filetree the page is reload and after the filetree is collapse. How I make filetree where after the page loading the filetree will expand in current location where is the file locate. thnx

Mato on May 23rd, 2008

Is there a ASP.NET (VB) connector?

Tried the C# and I am struggling with setting the directory correctly. For some reason it says the directory cannot be found. Tried it straight out of the box, with only directory changes. Any help is appreciated. Thanks.

Seth on May 29th, 2008

Hello ;-)

Just one thing:

It would be cool to put this code into php connector:
$ext = strtolower($ext);

What's the magic: the icons with uppercase extensions will appear :-P

Dalibor on Jun 4th, 2008

I'm trying out the Lasso connector. The file tree displays correctly but the callback does not display the file path and name in the alert box when the file is clicked. Could this be a flaw in the connector? Any ideas?

Rp on Jun 4th, 2008

Hi

Is it possible to do this :
When we click on a file, we are sent to a website

kpo on Jun 4th, 2008

Thank u for the great work. Was wondering how to go about keeping certain directories password protected. The scripts seem to override the .htaccess settings. Thoughts?

sam on Jun 12th, 2008

> Was wondering how to go about keeping certain
> directories password protected. The scripts seem to > override the .htaccess settings. Thoughts?
If I see right, this component is a JavaScript (so Client) side component in first place (and that was the hardest part to implement).
The communication protocol is described, and the "connector"s or the serverside code is there only as an example - you can extend and do what you want with it, thus allowing protecting as many directories as you want.

Demetrios Kyriakis on Jun 15th, 2008

I found a little hiccup in your file tree plug in. I am using ajaxSubmit form plug in to upload files to the directory tree. In the callback I reload your file tree plug in so the newly uploaded file appears. Works fine however when I click on the file name nothing happens. The feedback doesn't fire. Need to use livequery for binding the click events perhaps but not I'm not sure how that can be called within your plug in. Maybe you have a suggestion?

Rp on Jun 16th, 2008

The script is great. But it doesn't seem to work for Japanese/Chinese/Korean characters. Any help there?

BTW: Email addresses ended with info/name are valid too :)

Vincent on Jun 18th, 2008

Never mind on that ajaxSubmit callback problem. I was not executing the openFile(file) function in my callback which of course adds the click event to the file name. Oops. Working now.

Rp on Jun 20th, 2008

Wow! This is perfect. Just what I was looking for. Excellent job!

Chris on Jun 25th, 2008

hi,

I want to use this structure in windows explorer, for all my client files.
So don't want to use it on the i-net.

How? Please help.

Thanks,
Deniz

Deniz on Jun 26th, 2008

I am totally new to this. I have used the php tree from this site before but am not understanding this one. Where do I put the code in my page to create this tree.

matt on Jul 7th, 2008

Thank you for this great script. One question: I would like to start an AJAX-call when clicking a folder/directory/map. At this moment only an action is performed when clicking a file. Thank You in advance.

Allan on Jul 8th, 2008

@Allan
as a quick-and-dirty solution, just add:

o.folderclicked($(this));

and set folderclicked as option when you construct the tree.

For example:
$('#tree').fileTree({
root: '',
folderclicked: function(node) { alert(node.get(0).text); },
script: 'whatever.php' },
function(file) {
alert(file);
});
});

Richard van Zon on Jul 9th, 2008

@Allan
sorry, didn't quite tell you where to add the line. It's after line 73, above '} else {'

Richard van Zon on Jul 9th, 2008

Richard,

Thank You (Bedankt dus)! Works like a charm! Can you tell me if it is possible to hide files and only show maps.

Allan

Allan on Jul 13th, 2008

Richard,

Very strange, but it doesn't work anymore. I added the line: o.folderclicked($(this)); on line 73 before } else {.

When I construct the tree and click an folder I receive an Javascript Alert "Undefined".

My line: of code in het main programm:
"$('#fileTreeDemo_3').fileTree({ root: '../audio/audio/', script: 'jqueryFileTree.php', folderclicked: function(node) { alert(node.get(0).text); }, folderEvent: 'click', expandSpeed: 750, collapseSpeed: 750, expandEasing: 'easeOutBounce', collapseEasing: 'easeOutBounce', loadMessage: 'Bezig met laden...' }, function(file) {
alert(file);
});
.

Where's my error?

Allan on Jul 13th, 2008

Nice FileTree...
But still missing the sortable function :(

after 2 years nobody was able to get it right

mogio on Jul 16th, 2008

very thanks

klima on Jul 17th, 2008

1.I have downloaded the jquery.1.2.6.js.
But I don't know how to use it.
2.jquery file tree can list a folder automatically?
It is urgent,I need your help.

Thank you very much

Cherry on Jul 20th, 2008

Great!..so usefull and nice style. I downloaded for test

Felix on Jul 21st, 2008

Is callback "function(file){ alert(file); })" able to catch if the SHIFT button is pressed?

i.e.
if (evt.shiftKey!==1) alert("Here SHIFT has not been pressed")
else alert("Got a SHIFT-based event!")

eugeny on Jul 22nd, 2008

Hi, love this plugin.

I've come across an issue when using TinyMCE's plugin popup. Basically as soon as I include tiny_mce_popup.js the File Tree stops working. I'm lost as according to Firebug it still seems to be working but the data is never populating.

Any ideas?

Nick on Jul 30th, 2008

First let me say this script its bad ass!

I am a little confused as to why the PHP connector is not nearly as advanced as the PHP File Tree script.
I was hopping to be able to specify what file types to display. Is this feature planned or am i going to have to modify it?

John on Jul 31st, 2008

Superb!!!

Excelent!. Amazing.

Thanks,
gab

gab on Jul 31st, 2008

I love this plugin. It's great!
However, I have a question when I use it.
When I add a folder by using ajax PHP, how can I refresh the jqueryFileTree to display that folder?

Thanks!

user on Aug 2nd, 2008

Dear Cory S.N. LaViska!

Do you have an idea concerning callback "function(file){ alert(file); })" able to catch if the SHIFT button is pressed?

i tried this way

function(evt){
evt = (evt) ? evt : ((window.event) ? window.event : null);
if (evt.shiftKey!==1) alert("Here SHIFT has not been pressed");
else alert("Got a SHIFT-based event!");
})

but it doesnt work ):

Eugeny on Aug 4th, 2008

@Eugeny: This should help you out: http://www.simpltry.com/2007/01/04/shift-key-detection/

Cory S.N. LaViska on Aug 4th, 2008

I love this plug in but what is the best way to make the files downloadable once they are in the folders? I tried the openFile function but it didn't work.

tiffany on Aug 6th, 2008

@tiffany: Try this http://abeautifulsite.net/notebook/27

Cory S.N. LaViska on Aug 6th, 2008

@Nick: Sorry, I wasn't able to replicate the problem with TinyMCE. Send me some code if you like...

Cory S.N. LaViska on Aug 6th, 2008

I'm using asp, will that php work on that?

tiffany on Aug 7th, 2008

Is possible adapat the plugin to tree view (itens)?

Ju on Aug 12th, 2008

very cool stuff.

I have a problem though:

when i click a file the alert always shows the content 'file'. what am i doing wrong?

i use the following callback:

function(file){alert(file);}

thomas on Aug 18th, 2008

Love the treeview...

Ross on Aug 19th, 2008

Hello.
Is that possible that a specific directory initializes already opened?

Great job!!

Berkowitz on Aug 21st, 2008

How is use for open software ?

kbrothers on Aug 24th, 2008

Newb Question: I'm interested in passing the filename to a function like "openFile()", as mentioned above - and ultimately generating a link to the actual file for download purposes. I don't mind if the browser handles opening the file (opposed to opening a save-as prompt), but I would like it to open in a new window.

Can someone help me with the step-by-step process to generating a file download link onClick. Thanks in advance!

function openFile(file) {
// do something with file
}

$(document).ready( function() {
$('#container_id').fileTree({ [options] }, function(file) {
openFile(file);
});
});

Paul Jauregui on Aug 24th, 2008

Can the tree be populated by xml data

Rav on Aug 25th, 2008

// Open same page
function openLink(file)
{

window.document.location.href=fil ;
}
// Open new page

function openLink(file)
{
window.open(file); return false;
}



$(document).ready( function() {
$('#container_id').fileTree({ [options] }, function(file) {
openLink(file);
});
});

AddictDownload.com on Aug 26th, 2008

Pretty cool script but can't make it work with ASP.NET / C#

When I apply it to my ASP DropDownList it works, shows up and everything.. but when I submit I only get the first selected item... I figured I'd try with a ListBox... same thing happens! and yes I set multiple=multiple on the dropdown and selectionmode=multiple on the listbox..

can't get the data :( Any help?

thx

Mike on Aug 27th, 2008

^ you should delete the message above this one and this one... sorry

Mike on Aug 27th, 2008

You can achieve downloading a file with headers, in php:

include("../functions/returnmimetype.php");

header('Content-type: ' . returnMIMEType(basename($_GET["file"])));

header('Content-Disposition: attachment; filename="' . basename($_GET["file"]) . '"');

readfile($_GET["file"]);

Alex on Aug 28th, 2008

Hello - nice and simple - I like it.
Some questions about it - is it possible to start the tree openend a specific subdirectory?

Roland on Aug 28th, 2008

@Roland: Not presently. This may make it into version 2.0, though.

Cory S.N. LaViska on Aug 29th, 2008

I have a question, well maybe not just 1:

When I open the tree, I want to attach the ContextMenu to the folder and file (so I can give the option to delete, rename, create, ....)
I use this:
http://www.trendskitchens.co.nz/jquery/contextmenu/

However, I was not able to do it, I think it's because the tree was a bit slower than the contextMenu function, which caused a race condition.

I'm very new to this whole ajax+ jquery thing, so I will really appreciate it if you can point me to the right direction to solve this problem (and also some hints for the features I listed above: create, rename, etc.,,, would be great as well)

Regards

yellow1912 on Sep 2nd, 2008

Here is what I would like to see in an AJAX file tree:
* list folders and/or files. files are links
* allowOnly-/excludeOnly- files
* deletion of both files and folders (recursive)
* renaming of both files and folders
* simple usage
* easy to implement into other files. like 1 js, 1 ajax_updater and 1 demo file (css and images not counted)
* cross platform compatible
* cross browser compatible
* no DB required!

phpFileTree with jQuery is the closest. Aside from not being AJAX'ed it only needs rename and delete options

Kim on Sep 3rd, 2008

Hi, I really hope Cory or someone who has had this simaler problem reads but then again I am at the way bottom here so who knows.

I cant get this to work on my web server (apache2.2/PHP5/MySQL5)

When ever I configure everything out and try to go and preview it I get a PHP error:
"Undefined variable: root on line 21"

I really want to use this jquery file tree but its just now working.. can anyone please help me out there?

Devin on Sep 3rd, 2008

@yellow1912: I added these features in a number of custom CMS products using that same context menu (and one of my own) at least three or four times now. Alas, it can be a bit tasking and is not something that can quickly nor easily be explained. I am, of course, always available for hire if you would like to go that route.

@Kim: Thanks for your input. I'll keep these ideas (and all the other feedback I've received) in mind :)

@Devin: See my email to you.

Cory S.N. LaViska on Sep 3rd, 2008

This is a superb script!
Would love to see drag 'n drop, context menu and a small image preview feature for the 2.0 version.

Thank you for your hard work!

Andreas on Sep 5th, 2008

This plugin is great. However, I was experiencing a conflict as my global jQuery AJAX settings were set to expect the response as JSON objects.

Changing line 59 of the javascript file to the following prevented the conflict.

}, "html");

Thanks

Alex Torrance on Sep 8th, 2008

Great script! Nice work, but what's with the undefined $root variable in the jqueryFileTree.php script? It seems like maybe there should be a line at the top of the page something like this:

$root = $_SERVER["DOCUMENT_ROOT"];

That's what I had to do to get it working anyway.

Colin on Sep 11th, 2008

@Colin: you're right, $root should have had a comment or two about security and how to make the connector more secure. You can read more about it in the documentation on this page.

Cory S.N. LaViska on Sep 14th, 2008

Really looks great. I'll give you my feedback as soon as I try it. Thanks for it!

Valery Buchinsky on Sep 24th, 2008

great plugin, but i'm wondering if there is any way to trigger a directory collapse after clicking on an individual file.

thanks!

dave on Sep 25th, 2008

How hard it would be to convert this to a straight TreeView type control sourced from a div or ul?

p0s3r on Sep 25th, 2008

Nice Script..... you did a great job,

Is any plan to make items draggable?

Ratheesh on Sep 26th, 2008

Nice Script. I need it . Thank you.

tumaji on Sep 28th, 2008

i exactly copied the file as the demo page.
http://abeautifulsite.net/notebook_files/58/demo/

placed items in demo/demo as in the demo page

but it just wont work

tce on Oct 7th, 2008

tce, add $root = $_SERVER["DOCUMENT_ROOT"]; in jqueryFileTree.php and the script will work for you.

Mike on Oct 16th, 2008

The stuff done by you is superb.
But it is more relevent if you will handle the space in folde names.
i am also trying to resolve the same but as an ackonowledge i am informing you.
kindly give your suggetions in my mail id :

Diptirmaya Rout on Oct 16th, 2008

@Diptirmaya Rout Check out the demo, there are folders and files with spaces in them. Perhaps your particular application isn't handling spaces and other special characters properly. Maybe you need to use something like encodeURIComponent() or even something in your server side code.

Cory S.N. LaViska on Oct 16th, 2008

I love it! It's fantastic. Well done!

Paul Harvey on Oct 16th, 2008

Hello, this is a very nice tools.
But I would like to know if there are a possiblilty to have a connector for html hard coded like
<ul>1
<ul>1.1</ul>
</ul>

Manu on Oct 20th, 2008

How can i reload the tree once i add a new folder in the tree. I can't find any function regarding this issue. any help would be appreciated.

anunay on Oct 21st, 2008

I need a little assistance, or maybe you can tell me where to go.. :)
In the foreach clause of the jqueryFileTree.php I need to be able to filter out certain folders at the top level.
I provide reports to my customers and need to limit each customer to their folder.
Any help would be greatly appreciated.
Thanks.

Stephen on Oct 21st, 2008

guys, its simple to make it download. pass the get var of the file location to a download file such as this:

$('#fileTreeDemo_1').fileTree({ root: 'somefolder/', script: 'jqueryFileTree.php', folderEvent: 'click', expandSpeed: 750, collapseSpeed: 750, multiFolder: false }, function(file) {
window.open("download.php?file=" + (file));
});


now in download.php have this:


header('Content-type: ' . mime_content_type(basename($_GET["file"])));
header('Content-Disposition: attachment; filename="' . basename($_GET["file"]) . '"');
readfile($_GET["file"]);


it works very easily....

Darin

Darin on Oct 24th, 2008

I'd like to reiterate the security warning I posted in the article above. If you don't know what you're doing, you're best off not using a variable like Darin suggested. You have to understand the security risks and how to avoid them or else you risk potentially opening up your entire system for attack.

Be very careful when you start coding with these connectors!

Cory S.N. LaViska on Oct 26th, 2008

Hi,
Just wondering if its possible to get the full path to the selected folder? (ive added o.folderclicked($(this)); as explained by Allan - but this only gives the name of the folder clicked - not /the/path/to/folder)

Cheeers
Luke


Luke on Oct 30th, 2008

So, I guess you can't filter out specific folders at only the top level?

Stephen on Nov 3rd, 2008

This looks absolutely stunning! I will definitely do some expirimenting with this script! I might implement this in my cms. Thanks a lot for sharing!

Santhos Webdesign on Nov 3rd, 2008

hi, stumbled on this today and i am so happy that it does everything I want except one little thing.

I wanted to set this to be able to open plain old html, pdf and word documents. How can I achieve this.

A lot of the comments above mention code but not where to put it to im a bit lost! I am a complete beginner to coding as I deal with design only, so I would appreciate any help. thank you!
adeel.

adeel on Nov 3rd, 2008

@Stephen: you can modify the connector any way you want, including filtering out specific files/folders. It's best to keep this kind of feature inside the server-side script so malicious users can't get around it, which is why there isn't an option in the plugin itself.

Cory S.N. LaViska on Nov 3rd, 2008

Very nice and handy plug-in!
And very easy to get up and running!
I tried to use it so that when a file is clicked it's treated as a normal URL. Attempts to do it by removing the call-back function resulted in this error:
h is not a function
referring to this line:
h($(this).attr('rel'));

And from what I can see h is not declared to be anything anywhere.
This is the setup:
$('#filelist').fileTree({ root: '/test/', script: 'test.lasso' });

I suppose I have to reinsert the call-back function and have it call the URL.

Jolle on Nov 5th, 2008

Here is something cool todo:

To add a context menu you need add some lines inside the js so you can configure any callback function:

function showTree(c, t) {
$(c).addClass('wait');
$(".jqueryFileTree.start").remove();
$.post(o.script, { dir: t }, function(data) {
$(c).find('.start').html('');
$(c).removeClass('wait').append(data);
if( o.root == t ) $(c).find('UL:hidden').show(); else $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
bindTree(c);

// This is my
//******************
if( o.addedEvent != undefined )
{
o.addedEvent(data);
}
//******************

});
}


Now, after every connector call, the plugin will call the function that you set to the addedEvent property.
For ContextMenus you can use somethig like:

$('#browser').fileTree({
root: '/root/',
script: 'jqueryFileTree.aspx',
expandSpeed: 1000,
collapseSpeed: 1000,
addedEvent: function(data) {$(".directory A").contextMenu({
menu: 'menuFolder'
}, menuFolderCallback);}
}, function(file) {
alert(file);
});

Enjoy!

LRancez on Nov 6th, 2008

Oh... Im using this context menus:
http://www.trendskitchens.co.nz/jquery/contextmenu/

Cheers!

LRancez on Nov 6th, 2008

jaja sorry... wrong link actually the menu that Im using in the example is from this same site:
http://abeautifulsite.net/notebook/80

LRancez on Nov 6th, 2008

There is a slight error in the aspx connector provided. If your folder has a space in the name the jqueryFileTree.aspx file throws a wobbler. Just use the HttpUtility.UrlDecode() method when passing the folder string (dir) to the DirectoryInfo constructor.

e.g. (approx line 20 in jqueryFileTree.aspx)
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Server.MapPath(HttpUtility.UrlDecode(dir)));

Sean on Nov 6th, 2008

great script! +fav

got 1 question though... i have modified script to upload files/create folders w/ ajax... how do i refresh selected folder in tree, when "onSucess"?

co. on Nov 7th, 2008

Hi Cory,
I have some additional ideas for your consideration. It would be handy if you could add the ability to add addtional parameters to the POST. Also have a user definable function before/after bindTree(ca).

Thanks,
Nick

Nick Levett on Nov 7th, 2008

I found how to refresh some level of the tree from anywhere:

$('A[rel="' + #elementId# + '"]').parent().removeClass('expanded').addClass('collapsed');
$('A[rel="' + #elementId# + '"]').click();

Hope this helps :)

LRancez on Nov 7th, 2008

It did help. Thank you LRancez!

co. on Nov 7th, 2008

I found a more accurate way to refresh (the one posted before sometimes doesnt work):

$($('A[rel="' + #elementId# + '"]').parents('.directory')[0]).removeClass('expanded').addClass('collapsed');
$($('A[rel="' + #elementId# + '"]').parents('.directory')[0]).children('A').click();

cheers!

LRancez on Nov 10th, 2008

Hi all,
@Richard,
how do I get the full path of the folder ? and not just the folder name...
Thanks
___________
@Allan
as a quick-and-dirty solution, just add:

o.folderclicked($(this));

and set folderclicked as option when you construct the tree.

For example:
$('#tree').fileTree({
root: '',
folderclicked: function(node) { alert(node.get(0).text); },
script: 'whatever.php' },
function(file) {
alert(file);
});
});
________________

KlerMor on Nov 11th, 2008

The demo it's not working it is a shame because i think this suits me but i cannot see it :-(

Angelo Moreira on Nov 12th, 2008

@Angelo: sorry about that, we just moved to a new dedicated server and I obviously forgot to update the path in the demo. It's working now :)

Cory S.N. LaViska on Nov 12th, 2008

for folders:

this gives you the current folder name:
o.folderclicked($(this));

and this gives the full path:
o.folderclicked($(this).attr('rel'));

Sean on Nov 12th, 2008

@Sean : thanks !

KlerMor on Nov 13th, 2008

I've patched the php to connector to run on php4 server.

<?php
//
// jQuery File Tree PHP Connector
//
// Version 1.01
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 24 March 2008
//
// History:
//
// 1.01 - updated to work with foreign characters in directory/file names (12 April 2008)
// 1.00 - released (24 March 2008)
//
// Output a list of files for jQuery File Tree
//

$_POST['dir'] = urldecode($_POST['dir']);
//
$directory = $_POST['dir'];

if( file_exists($root . $_POST['dir']) )
{
//
if( !function_exists('scandir') )
{
function scandir($directory, $sorting_order = 0)
{
$dh = opendir($directory);
//
while( false !== ($filename = readdir($dh)) )
{
$files[] = $filename;
}
if( $sorting_order == 0 ) {
sort($files);
} else {
rsort($files);
}
return($files);
}
}

$files = scandir($root . $_POST['dir']);
natcasesort($files);
//
if( count($files) > 2 )
{ /* The 2 accounts for . and .. */
echo "<ul class=\"jqueryFileTree\" style=\"display: none;\">";
// All dirs
foreach( $files as $file )
{
if( file_exists($root . $_POST['dir'] . $file) && $file != '.' && $file != '..' && is_dir($root . $_POST['dir'] . $file) )
{
echo "<li class=\"directory collapsed\"><a href=\"#\" rel=\"" . htmlentities($_POST['dir'] . $file) . "/\">" . htmlentities($file) . "</a></li>";
}
}
// All files
foreach( $files as $file )
{
if( file_exists($root . $_POST['dir'] . $file) && $file != '.' && $file != '..' && !is_dir($root . $_POST['dir'] . $file) )
{
$ext = preg_replace('/^.*\./', '', $file);
echo "<li class=\"file ext_$ext\"><a href=\"#\" rel=\"" . htmlentities($_POST['dir'] . $file) . "\">" . htmlentities($file) . "</a></li>";
}
}
echo "</ul>";
}
}
?>

serialbob on Nov 13th, 2008

Thank´s for the script.
I´ve inserted in row 59: o.afterExpand();
So ist´s possible to call a function afer expanding (in my app to register a context menu).
Maybe a idea for the next version?!

Sven on Nov 17th, 2008

Hi Its a nice script, have anyone tried drag n drop cart with this?. Please could anyone help me out?? I need a drag & drop cart as in Relay Ajax directory Manager http://ecosmear.com/relay/ . Please help me out!

shiva on Nov 18th, 2008

how do you keep the state when the page is reloaded????????? i.e. i post a back to the page using a href and the state changes and the folders collapse.

<?php
session_start();
?>
<style>
#screenshot{
position:absolute;
border:1px solid #ccc;
background:#333;
padding:5px;
display:none;
color:#fff;
}


</style>
<script type="text/javascript">
google.load("jquery", "1.2.3");
</script>
<script src="js/main.js" type="text/javascript"></script>

<?php
require_once("scripts/defs.php");
require_once("scripts/database.php");
require_once("scripts/routines.php");
require_once("scripts/debug.php");


/*****************************************************************************/
/*****************************************************************************/
if (($connection = getObjectsConnection()) != NULL)
{
$_POST['dir'] = urldecode($_POST['dir']);
/*****************************************************************************/
/*****************************************************************************/
if( file_exists($root . $_POST['dir']) )
{
$files = scandir($root . $_POST['dir']);
natcasesort($files);
/*****************************************************************************/
/*****************************************************************************/
if( count($files) > 2 )
{
echo "<ul class=\"jqueryFileTree\" style=\"display: none;\">";
// All dirs
/*****************************************************************************/
/*****************************************************************************/
foreach( $files as $file )
{
if( file_exists($root . $_POST['dir'] . $file) && $file != '.' && $file != '..' && is_dir($root . $_POST['dir'] . $file) )
{
echo "<li class=\"directory collapsed\">
<a class=\"directory_titles\" href=\"#\" rel=\"" . htmlentities($_POST['dir'] . $file) . "/\">" . htmlentities($file) . "</a>
</li>";
}
}
// All files
/*****************************************************************************/
/*****************************************************************************/
foreach( $files as $file )
{
$new_file = str_replace("_"," ", $file);
/*****************************************************************************/
/*****************************************************************************/
if( file_exists($root . $_POST['dir'] . $file) && $file != '.' && $file != '..' && !is_dir($root . $_POST['dir'] . $file) )
{
$results_video_details = getAllVideoDetails($file, $connection);
$results_object_details = getAllVideoObject($results_video_details[TABLE__VIDEOS__VIDEO_ID], $connection);
$results_video_object_details = displayVideoObjectDetails($results_video_details[TABLE__VIDEOS__VIDEO_ID], $connection);



//$size = filesize(REPOSITORY.$_POST['dir'].$file);
$ext = preg_replace('/^.*\./', '', $file);
echo "<li class=\"file ext_$ext\">";
if ($results_video_object_details !=NULL)
{
$count = 0;
foreach ($results_video_object_details as $key_picture => $value_picture)
{
$count++;
if ($count > 1)
{
/**/
//debug("here".$count);
}
else
{
echo "<a href=\"#\" class=\"screenshot\" title=\"".$new_file."\" rel=\"./images/video_images/".$results_object_details[TABLE__OBJECT__DIRECTORY]."/".$value_picture."\">
<img src=\"./images/video_images/".$results_object_details[TABLE__OBJECT__DIRECTORY]."/".$value_picture."\" width=\"10px\" height=\"10px\" border=\"0\"/>
</a>";
}
}
}
echo "<a class=\"list_item\" href=\"index.php?title=".$file."&directory=".$_POST['dir']."&runtime=".$results_video_details[TABLE__VIDEOS__VIDEO_RUNTIME]."&videoid=".$results_video_details[TABLE__VIDEOS__VIDEO_ID]."\">".RemoveExtension(htmlentities($new_file))."</a>&nbsp;<font class=\"runtime\">".$results_video_details[TABLE__VIDEOS__VIDEO_RUNTIME]."</font>";
echo "</li>";
//print_r($results_object_details[TABLE__OBJECT__DIRECTORY]);
//print_r($results_video_object_details[1]);

//if ($results_video_object_details !=NULL)
// {
// $count = 0;
// foreach ($results_video_object_details as $key_picture => $value_picture)
// {
// $count++;
// if ($count == 11)
// {
// /**/
// }
// else
// {
// echo "<a href=\"#\" class=\"screenshot\" title=\"".$new_file."\" rel=\"./images/video_images/".$results_object_details[TABLE__OBJECT__DIRECTORY]."/".$value_picture."\">
// <img src=\"./images/video_images/".$results_object_details[TABLE__OBJECT__DIRECTORY]."/".$value_picture."\" width=\"10px\" height=\"10px\" border=\"0\"/>
// </a>";
// }
// }
// }
}
}
echo "</ul>"; // must be below the foreach loop or this will ause loads of endless loops of the same data
}
}
mysql_close($connection);
}


function countimages()
{

}
?>

olly on Nov 18th, 2008

Hi, my problem is parameter passing.
I want to use
<li class="file ext_php"><a href="#"> as a # sign I want to put some ID numbers and after I clicked Tree Items I want to take that number. Is there any posibilities to do that ? Thanks for the help.

ALexa on Nov 19th, 2008

this plugin not work for me, but this link http://abeautifulsite.net/notebook.php?article=21 worked !! thank you for share your brilliant idea and skill :))

dr.emi on Nov 21st, 2008

I'm working in a framework (Oracle Application Express) that has it's own AJAX methods for getting data. My goal is to call these methods instead of a file-based connector script (there are no files in this framework). So, lets say I have a function called "foo" that returns an AJAX response with the data. Can you provide a quick example of how you would call it?

I have this mostly working, but it's VERY hacked and I want to do it right.

Thanks,
Tyler

Tyler on Nov 21st, 2008

Second question. I'm using the example from comment #114 by LRancez to add context menus to the tree. For some reason on the first page load, the context menus only get attached to the folders, not the files. Once I click a sub-folder, the menu is attached to the new files. Very odd. Any thoughts?

Also, it would be nice to attach a different context menu to a file and a folder, can someone provide an example for this?

Thanks again,
Tyler

Tyler on Nov 21st, 2008

Hate to do this, but "bump". I'm really stuck right now. Any help would be greatly appreciated.

Tyler on Nov 24th, 2008

Guys, I am willing to post more parameters to php connector not just the path.

Any help will be appreciated.

By default it is posting 'dir' parameter and I can't find a way to post 'x' parameter along with it..

(for the curious ones, i am connecting to different drives and to different root folders on the same page, and after a directory click i should be able to pass a parameter to connector which drive that dir belongs.)




demianus on Nov 25th, 2008

To be more exact, i need to post the 'id' of each folder that is clicked.

//jqueryFileTree.js line 60
$.post(o.script, { dir: t, id : '???'},

I know I can post a second and third variables like above, but i can't get the id of the folder instead of ???.

I am currently stuck please donate your good will. I'll appreciate it.

demianus on Nov 25th, 2008

I'm going to try to get this to work with Stellent (now called Oracle UCM)...this should be fun, wish me luck!

Vincent LePes on Nov 26th, 2008

@Vincent LePes Good luck!

Cory S.N. LaViska on Nov 27th, 2008

Hello!

It´s a beautiful work! really!

I have only one question...

When I klick a file I get a javascript-msgbox with the path of this file.(You clicked on...)
So I want do the same with a folder. How can I do it???

Can somebody help me???

Thx
My regards.

miba on Nov 29th, 2008

very nice, but I don't understand why this nice js tree is only limited to filesystems :/

Daniel on Nov 30th, 2008

Does ASP.NET connector works in medium trust?

Biagio on Dec 2nd, 2008

I want to expand a particular menu from other panel by clicking a link, is it possible? Here is the link below. JqueryFileTree menus in the left panel and the link on which i want to click to expand a particular menu on the left panel is on the main panel. Like:

Main page shortcuts to trigger ajax sliding menus:
1. Equipment rentals should open up the ELECTRICAL/LIGHTING DEPT dropdown
2. Locations should open LOCATIONS DEPT
3. Cast & Crew - switch to CAST & CREW dropdown, select CASTING DEPARTMENT dropdown.
4. To Get Started, Click a category on the left... should open up ARTIST/BAND MANAGEMENT

http://peepthescene.com/peep411.php

Thanks in advance.

Shahriat on Dec 3rd, 2008

Thanks for a wonderful plugin.
I have a question regarding the tree refresh. I integrated your context menu plug-in to allow user to create and delete directories. The problem is whenever a folder is created/deleted the tree doesn't refresh. I tried the solution mentioned by @LRancez but it sometimes doesnt work. Specially when there are more than one folder in the list.

Is there a better way to refresh the tree so that it reloads everything.

Thanks in advance.

amir on Dec 3rd, 2008

how to load data from xml?

ekid on Dec 6th, 2008

very nice script =)
only missing a few things like drag file to other folder functionality and a event dispatched on create completion would be nice as well

tho then again i could move ma'h light ass and modifie it myself haha, i'l message if i do xD

bara on Dec 9th, 2008

Very goo script; I use it with a tree of category and files from a db; (i have rewrite the engine of connector).
I wait for some features as "save tree state in cookie" and "collapse full tree" in the next version.
Is there an indicative date for release 2.0 ?
Thanks.

Marco Mocellini on Dec 11th, 2008

Just wanted to follow-up and post my code for adding one type of context menu to the Files and another menu to the Folders. This is for the context menu on this site:
http://abeautifulsite.net/notebook/80

if( o.folderEvent.toLowerCase != 'click' ) $(t).find('LI A').bind('click', function() { return false; });
// tyler added context menu here
$(t).find('LI.directory A').contextMenu({
menu: 'directoryMenu'
}, function(action, el, pos) { alert('ok'); } );

$(t).find('LI.file A').contextMenu({
menu: 'fileMenu'
}, function(action, el, pos) { fileActions(action,$(el).attr('id')); } );
// end context menu tyler



Tyler on Dec 11th, 2008

I've got the same error like Devin:

"Undefined variable: root on line 21"

Please help. Thanks!

Simon on Dec 18th, 2008

I modified the Cory's great script as follows:

......

var assArray = [];

$(this).each(function() {

function showTree(c, t) {
$(c).addClass('wait');
$(".jqueryFileTree.start").remove();
if (assArray[t] == undefined) {
$.post(o.script, { dir: t }, function(data) {
assArray[t] = "";
checkData(c, t, data);
});
} else {
checkData(c, t, null);
}
}

function checkData(c, t, data) {
$(c).find('.start').html('');
$(c).removeClass('wait')
if (data != null) { $(c).append(data); bindTree(c); }
if (o.root == t) $(c).find('UL:hidden').show(); else $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
}

.......

I'm not a javascript programmer but it seems to work. In this way when you click on a folder for the second time to open it, the script doesn't load data again.
A new parameter could be added to enable or not the "cache".

Cory is it correct?

Marco on Dec 20th, 2008

I forgot:

this line has to be commented in bindtree function:

$(this).parent().find('UL').remove();

Marco on Dec 20th, 2008

Good method, thanks the author. Only I can not understand how to connect a script???

Douson on Dec 24th, 2008

@Tyler (11th dec 2008):
When using the default connector then you should replace $(el).attr('id') with $(el).attr('rel') if you want to have the absolute path of a file.

Janm on Dec 28th, 2008

Many thanks for this great work.

I couldn't find a MySQL connector, so I wrote one using a MySQL based virtual file system. If anybody is intrested in such a connector, here come a little script I am using for my application:

<?php
# assumed there is already a working SQL connection.

$folder=$_POST['dir'];

echo '<ul class="jqueryFileTree" style="display: none;">';
$query = "select * from folders where parent='$folder' and user='$user'";
$result = mysql_query($query);
if ($result) {
while ($row = mysql_fetch_object ($result)) {
echo '<li class="directory collapsed"><a href="#" rel="' . $row->id . '/">' . $row->name . '</a></li>';
}
}

$query = "select * from files where parent='$folder' and user='$user'";
$result = mysql_query($query);
if ($result) {
while ($row = mysql_fetch_object ($result)) {
echo '<li class="file"><a href="' . $row->id . '" target="_blank">' . $row->title . '</a></li>';
}
}
echo '</ul>';

?>

Stefan on Jan 3rd, 2009

I like Marco love this code! However, i'd love to know about version 2.0 as I think this code will really come in handy, especially with the cookie feature as I use this as a navigation and it is annoying having the menu collapse everytime.

Any idea when (or a rough guess!) the next release will occur?

Jason on Jan 7th, 2009

Hello.
Is there any possibility to use this great script to display document trees based upon queries. ? I should use it for a document management system.
Thanks in advance!

Sergio on Jan 15th, 2009

nice article i like this examples


thanks
www.csshook.com

jon on Jan 16th, 2009

@Sergio, sure, you just have to write a custom connector. I'm using in Oracle Application Express and my data source is a query.

Tyler on Jan 16th, 2009

Whole filetree refresh

this is in your html
<div id="filetree"></div>
<input type="button" onClick="refresh_whole_filetree();">

this is in your js

function refresh_whole_filetree(){
$('#ftp_filetree').fileTree({
root: '/',
script: 'kodingen/js/jqueryFileTree.php',
expandSpeed: 1000,
collapseSpeed: 1000,
multiFolder: true
},
function(file) {sendFileToEditor(file);}
);
}

this will refresh the whole div that your filetree shows.
cheers.


devrim on Jan 19th, 2009

replace #ftp_filetree with #filetree on my comment above. and you dont need function(file) {sendFileToEditor(file), sorry i just copied and pasted from our codebase. hope to be of help.

devrim on Jan 19th, 2009

I have tried to get the folder click to work but I am just not getting it. Does any one else have it working?

$(document).ready( function() {

$('#container_id').fileTree({ root: 'c:/',folderclicked: function(node) { alert(node.get(0).text); }, script: 'jqueryFileTree.cfm' }, function(file) {
alert(file);
});

And in the script after line 73
o.folderclicked($(this).attr('rel'));

In fire bug it tells me node.get is not a function.

Mike on Jan 21st, 2009

This is fantastic, I can't believe I haven't found this until now. Thanks so much for this nifty plugin!

NetOperator Wibby on Jan 22nd, 2009

This thing is absolutely beautiful and absolutely what I wanted, thanks!

Albert on Jan 23rd, 2009

Hi, when i use the directory path a /default/test/ and root as '/' it repeatedly shows the folder as subfolder of itself. Also, it shows the file at the same level as the parent folder. What am i doing wrong?
<div class='filetree'>
<ul class="jqueryFileTree" style="display:none">
<li class="file ext_pdf">
<a href="#" rel="/Default/test/Delware Corp Fees.pdf">Delware Corp Fees.pdf</a>
</li>
<li class="directory collapsed">
<a href="#" rel="/Default/test/">test</a>
</li>
</ul>
</div>
the script function that i am attaching to my div is as follows...
$('.filetree').fileTree({
root: './images',
script: 'showFileTree.do',
expandSpeed: 250,
collapseSpeed: 250,
multiFolder: true
}, function(file) {
//alert(file);
listFiles(file);
});

R on Jan 23rd, 2009

Thank you for your work.

Is there a way to only show folders (no files), so I may use it as a folder picker? Probably set it up as one click expand, two click to select, or perhaps a button to select current folder...

Brett Slaski on Jan 23rd, 2009

This is great, I'm trying to link it to a FileMaker database using php. Anyone care to post a MySQL download (preferably with context Add Delete and Rename) so I can disassemble it and recreate it for my FileMaker database. Sorry to be a noob, but still learning about this stuff and I tend to learn from examples I can pick apart.

Cheers

Abs on Jan 27th, 2009

Amazing. I love the look and functionality of it in the demo. The only thing is(and I know it's my fault not yours), is that I cannot for the life of me get this to work, I have set the $root = $_SERVER['DOCUMENT_ROOT];... as well as trying to manually assign it to for ex: /public_html/, then in the .html set it to /images/, it still doesn't work. If someone could maybe help me, it'd be greatly appreciated, my email is Kobetouchedme@yahoo.com

Nathaniel on Feb 1st, 2009

It's great. But i have a question. How to add a multiselect for files (on CTRL click )?

denisK on Feb 2nd, 2009

Does anyone have example code for opening the clicked-on file? I have searched and searched and found nothing....

Bill on Feb 2nd, 2009

Hello:

First of all: great job! I've successfully integrated jQuery FileTree with a Struts2 action, accessing to a database for retrieving the tree structure. The only problem I've had is related with this line in the script:

showTree( $(this).parent(), escape($(this).attr('rel').match( /.*\// ))

I've had to modify this because I don't use folder names, but numbers (id's) for accessing database and retrieving the child nodes. The line I use is simpler:

showTree( $(this).parent(), escape($(this).attr('rel')));


My custom script plugin for Struts 2 is:

<%@ taglib prefix="s" uri="/struts-tags"%>
<ul class="jqueryFileTree" style="display: none;">
<s:iterator value="itemList">
<s:if test="%{elementIsFolder}">
<s:set name="class_li" value="%{'directory collapsed'}"/>
</s:if>
<s:else>
<s:set name="class_li" value="%{'file ext_file'}"/>
</s:else>
<li class="<s:property value="#class_li"/>">
<a href="#" rel="<s:property value="elementId"/>">
<s:property value="elementName"/>
</a>
</li>
</s:iterator>
</ul>


I don't invoke the plugin directly. This is only a render template. The real plugin is the action, whose is invoked in this way:

$('#divTree').fileTree({ root: '', script: '/MyApp/myNamespace/getTree.action' }, function(file) {
alert(file);
});

The action must be correctly mapped in struts.xml, with the "success" result redirecting to the jsp above.

This action needs to have two get-set method, for "dir" parameter, and for "itemList", that is an element collection. Each element is a POJO with three attributes: elementId, elementName and elementIsFolder. The element database retrieving is up to you.

I hope this code helps someone. Cheers ("Saludos a todos")

Carlos.

Carlos on Feb 5th, 2009

Hello again:

I need some help. I want to use the jqueryContextMenu plugin (http://abeautifulsite.net/notebook.php?article=80) and the jqueryFileTree plugin, running on the same page. Enabling them separately, both works fine, but if I enable both at same time (in document.ready function) it only works the fileTree. Do you know what could be happening?

Thanks in advance:

Carlos.

Carlos on Feb 5th, 2009

Wow, looks great. I really want to learn Jquery! Good job guys.

Q5 Webdesign on Feb 5th, 2009

Excellent job. I love it!

Does anybody have the following issue? when clicking a "collapsed folder" it shows the content and the open file icon is displayed. when clicking again to close it it is leaving a blank line between the folder and the following file in the list. I reviewed the js file to check if this has to be with the "collapsed" or "expanded" class but could not find anything.

Thanks in advance,
Kenia

Kenia on Feb 5th, 2009

I'm having trouble getting the full folder path when a directory is expanded. I can get the name of the selected folder in an alert() box but the full path doesn't show up.

I tried the following line but it doesn't work.
o.folderclicked($(this).attr('rel'));

Nathan

Nathan Brown on Feb 6th, 2009

Update:

I had to also change the line (by removing the node.get(0).text)

folderclicked: function(node) { openFolder(node); }

Nathan Brown on Feb 6th, 2009

hi , i want to create the tree with dynamic data.means if we click the link it will show a table contain with db data.Any body have sample code.

usman on Feb 11th, 2009

Hi,
thanks for the great script! After some tweaking I got it to work as I expected.

I have one question: I want a couple of <a>-links in the same <li>-element as the link to a file. These links shall serve as tools for removal or show an image instant in the web browser.

But it seems like my Javascript can't reach the links in the <li>! I've tested all kind of methods now; putted the script inline in the <head>, tested <buttons> and more.. I simply can't reach them! The page only updates and do nothing.
Has anyone a suggestion?

John on Feb 11th, 2009

@usman, it would probably help to specify the database (MySQL, MS SQL Server, Oracle, etc) and what front-end (PHP, Ruby, J2EE, .Net) you are using. I have this working with Oracle and Application Express, but unless you are using those, my code will be of no use. If you look near the top of the page under "Custom Connectors", he tells you the HTML you need to write. It's just a matter of say writing a PHP page that will query your MySQL database and return that HTML.

Tyler on Feb 12th, 2009

Hello Guys,

I've made a custom connector that produces code like underneath. I have two problems which I can't get my head around. The first one is that Apple should be the folder and Ipod and Macbook should only be visible whenApple is clicked. Instead all my 'child' elements seem to be in the root. Can someone point in me in the right direction please....

Secondly, I can click on Apple, and then I get my root elements appear one level lower, so I click on apple again, and again.....and it continues. How can I stop this behavior?

<ul class="jqueryFileTree" style="display:none">
<li class="directory collapsed"><a href="#" rel="/cms">Apple</a></li>
<li class="file ext_ppt"><a href="#" rel="/cms/filename.ppt">IPod</a></li>
<li class="file ext_ppt"><a href="#" rel="/cms/filename.ppt">Macbook</a></li>

<li class="directory collapsed"><a href="#" rel="/cms">Microsoft</a></li>
<li class="file ext_ppt"><a href="#" rel="/cms/filename.ppt">Office</a></li>
<li class="file ext_ppt"><a href="#" rel="/cms/filename.ppt">Windows</a></li>

<li class="directory collapsed"><a href="#" rel="/cms">Adobe</a></li>
<li class="file ext_ppt"><a href="#" rel="/cms/filename.ppt">Photoshop</a></li>

<li class="directory collapsed"><a href="#" rel="/cms">Dell</a></li>
<li class="file ext_ppt"><a href="#" rel="/cms/filename.ppt">Latitude D820</a></li>

</ul>

Many Thanks

Abs

Abs on Feb 12th, 2009

Any news on whether the new version will include cookies to store previous state of the file structure, i.e. which ones where open etc.

I was thinking about having a go and changing the code myself but if its nearly done then ill wait for release.

Jason on Feb 12th, 2009

can it work from right to left?

mahmoud on Feb 15th, 2009

I wanted to run this on my local harddrive showing c:/ or e:/

I was required to add this line
from
function showTree(c, t) {
to
function showTree(c, t) {
t = t.replace('%3A',':'); // convert escape to colon

-=Dan=- on Feb 15th, 2009

Hello, the plugin is wonderful but how do i make filenames downloadable when clicked?
Instead of just reading name on alert
Be nice, I am a total newbie :-)
Many thanks

Gattis on Feb 24th, 2009

For forcing a download, this seems to work for me and I don't see any security risk so far.

Remove the callback function from the js and add the link to the file in the <a> tag of the file instead of "#" in the connector.

Brandon on Feb 24th, 2009

Hi,

Excellent script, congrats.
Question: what could be the reason that some of the folders seems to be empty when you click on them, but the actual folders have a lot of files (pdf) but they don't show.

Thanks for your help and great script
Regrds,
Alejandro.

Alejandro Barrere on Mar 1st, 2009

Hi,

The problem seems to be that it doesn't like spaces on the folder names.
Any ideas how to fix that.

Regards,
Alejandro.

Alejandro Barrere on Mar 1st, 2009

Awesome. absolutely love this plugin, and im not even going to say 'would be better if you added x,y and z'.

I think its simplicity is what makes it so great....not a recursive function in sight!! :-D

just plugged this in to work via ASP classic, with database calls for folders and files rather than a phyiscal folder directory...works like a charm.

Brilliant.

Carl on Mar 5th, 2009

$('#clientfiles').fileTree({ root: '/admin/clients/*****' , script: 'jqueryFileTree.php' }, function(file) {
    openLink(file);

**** - I need to insert a dynamic name in here using php, eg. /admin/clients/client1/ where client1 is the variable.

Any advice would be much appreciated :)

sam on Mar 5th, 2009

Just cracked it!

var myPhpVar = "<?php echo ($clientfoldername); ?>";


  $('#clientfiles').fileTree({ root: '/admin/clients/' + myPhpVar + '/' , script: 'jqueryFileTree.php' }, function(file) {
    openLink(file);
   });

sam on Mar 5th, 2009

Hi, has anyone managed to successfully connect this to a php database? If so, how did you store the details of the folder structure hierarchy and what requests did you make to 'drill' dow the tree.

So far I've got the root folders and files to display in my tree, but I can't seem to get beyond this....any help would be very much appreciated. (Is it possible to load the entire tree in one go?)

Thanks

Kaz

Kaz on Mar 8th, 2009

Very nice job!!! I've implemented your treeView in combination with JQueryContextMenù and all works well under Ajax.
The problem is: when i click other controls the page posts back and the treeView reloads with all nodes collapsed...
How to force Expand event???

Roberto on Mar 11th, 2009

Ia ma testing that nice work in a PWS.
I want to provide download facility
Perhaps a music site....////

mofazzal on Mar 12th, 2009

Sorry, what is the syntax to force the call to the function to expand a node?

Roberto on Mar 13th, 2009

very good, thanks

sivas on Mar 15th, 2009

Hello all,

I've created a custom connector with the code underneath. This links to my db and creates a filetree as expected. The 'only' problem is when I click on a folder to expand it, it expands opening up the entire tree from the root, from the folder that is clicked, and I can do this many times. How do I stop it so it only opens up a subset of folders from that branch. Hoping there is a really quick answer for this.

This is my connector.

/* I've removed the username password and select * statement that finds ALL the records. I know his is working well, as it does produce the tree I want, the problem only arises when I click a collapsed folder, it generates the tree from the root in the branch I am expecting a subset of data. */

<ul class="jqueryFileTree" style="display: none";>
<?php foreach($rsContent_result->getRecords() as $rsContent_row){ ?>
<?php

$type = $rsContent_row->getField('TYPE',0);

If($type=="FOLDER"){
echo '<li class="directory collapsed"><a href="#" rel="">'.$rsContent_row->getField('Title',0).'</a></li>';
} else {
echo '<li class="file ext_ppt"><a href="#" rel="">'.$rsContent_row->getField('Title',0).'</a></li>';
} ?>
<?php } ?>
</ul>

Many Thanks

Abs on Mar 15th, 2009

Just wanted to say thanks for this lovely plug-in. Brilliant work - but even better than the brilliance is the excellent demo, documentation, and readability of the code. Thanks also to @LRancez for the tip.

@Roberto you may find @LRancez's post helpful

$($('A[rel="' + #elementId# + '"]').parents('.directory')[0]).removeClass('expanded').addClass('collapsed');
$($('A[rel="' + #elementId# + '"]').parents('.directory')[0]).children('A').click();

where you replace #elementId# with the path to the directory will expand that directory. You'll probably have to iterate through the full path to expand the parent directories first.

Anne on Mar 15th, 2009

@Abs try populating the rel attribute in your code with something meaningful, like the path to the directory?

Anne on Mar 15th, 2009

@ Anne,

Many Thanks for your suggestion. the a attribute will be a record id, once I've got going.

I've created a separate fictitious 'static' ul folder structure so can understand what is going on. Any ideas what I would type in the a attribute here (bearing in mind this is a static file). Once I've got it working I'll move back to my database. At this point just interested in getting it to open only the 'excel documents' branch when I click on the excel docs folder.

Any ideas

<ul class="jqueryFileTree" style="">
<li class="directory collapsed">
<a rel="documents" style="position: static;">documents</a>
<ul>
<li class="directory expanded" style="position: static;">
<a rel="documents/excel docs/" href="">excel docs</a>
<ul class="jqueryFileTree" style="display: block;">
<li class="file ext_xls">
<a rel="documents/excel docs/accounting.xls" href="#">accounting.xls</a>
</li>
<li class="file ext_xls">
<a rel="documents/excel docs/ar.xls" href="#">ar.xls</a>
</li>
<li class="file ext_xls">
<a rel="documents/excel docs/billing.xls" href="#">billing.xls</a>
</li>
<li class="file ext_xls">
<a rel="demo/documents/excel docs/math.xls" href="#">math.xls</a>
</li>
<li class="file ext_xls">
<a rel="demo/documents/excel docs/personal finances.xls" href="#">personal finances.xls</a>
</li>
</ul>
</ul>

Abs on Mar 16th, 2009

I need some help. I am not so good with javascript or jquery..

I modified this script to get information about virtual folder in my database. It works well.

Now i added external serch option to my files and folders and the format of the result is the same as the format that uses this script. And when i preform a search this script doesnt work anymore.

So:

Page opens
->Shows the files and folders list
->Do some actions on files and folders and it works
->Do some ajax search and populate the same container with data
->script doesnt work.

Can anyone help me??

c0d3r on Mar 16th, 2009

I feel a little stupid saying this (it was the first jQuery + ajax script for me), but after an hour of unsuccessful trials, I realized that the connector file has to be *moved* in the same directory of the script........
This will be obvious for all of you, but who knows there's someone stupid as much as me in the world!

Giovanni on Mar 21st, 2009

I have completely rewritten your FileTree with dozen of improvements, please look at:
http://overdesign.net/p/jfiletree/
Thanx a lot for inspiration.

artico on Mar 23rd, 2009

Hi,

This was a nice plugin I have tried your's with asp but it was not calling the asp file i tried a lot on this may i know where i am wrong on this. Please help. Urgent.


<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>;
<html xmlns='http://www.w3.org/1999/xhtml'>;
<head>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1' />
<title>Untitled Document</title>
<script src='jquery.js' type='text/javascript'></script>
<script src='jquery.easing.js' type='text/javascript'></script>
<script src='jqueryFileTree.js' type='text/javascript'></script>
<link href='jqueryFileTree.css' rel='stylesheet' type='text/css' media='screen'>
<script type='text/javascript'>
$(document).ready
(
function()
{


$('#fileTreeDemo_3').fileTree
(
{
root: 'sixsiteadmin/',
script: 'connectors/jqueryFileTree.asp',
folderEvent: 'click',
expandSpeed: 750,
collapseSpeed: 750,
expandEasing: 'easeOutBounce',
collapseEasing: 'easeOutBounce',
loadMessage: 'Un momento...'
},
function(file)
{
alert(file);
}
);

}

);

</script>
</head>

<body>



<div class='example'>

<div id='fileTreeDemo_3' class='demo'>
</div>
</div>

</body>
</html>

Subhashini on Mar 25th, 2009

Need help to write the jquery code to perform the operations like creating new file,copy,upload,delete and rename.
Any kind of code help is appriciated.
Thanks in advance,
Raghuram

Raghuram on Apr 1st, 2009

i'm not really sure i get dan's example of showing local files. i would like to try to use this to browse a local hard drive. any advice is greatly appreciated. thanks.

jamie on Apr 1st, 2009

Love the script. I'm using it to implement a kind of decision making app - plenty of yes/no answers.

Does anyone know a way to implement different icons for different folders? If possible, preferably based on the name of the folder. I think it could be done by toying around with the connector file and setting up new extensions (I'm using php) but I think I need a bit of guidance. Any takers?

Ciaran on Apr 2nd, 2009

@Ciaran: Modify the connector to append another class to each directory that gets outputted (based on name, or whatever criteria you wish). Then you can add the classes to your CSS file to change the image.

Cory S.N. LaViska on Apr 2nd, 2009

Great! Got it working - and now to hide the file extensions... hmm :P

Ciaran on Apr 2nd, 2009

Don't work with spaces and special characters in ASP.

Virgulino on Apr 2nd, 2009

Hi,
I want to know how to capture the corresponding folder/directory path when it is clicked(on load directory listing is happening with the jquery file tree plugin).
your response will be appreciated.

Thanks in advance,
Raghuram Reddy Gottimukkula,
Bangalore

Raghuram Reddy on Apr 3rd, 2009

To work in ASP with spaces and special characters in folders and files names, I make this change in the function "bindTree()":
- showTree( $(this).parent(), escape($(this).attr('rel').match( /.*\// )) );

- showTree( $(this).parent(), $(this).attr('rel').match( /.*\// ) );

I remove the scape() function because the asp not encode the "rel" attribute. So we don't need to scape/encode him.

If someone found something wrong, please tell me.

Virgulino on Apr 3rd, 2009

Thanks Virgulino

Raghuram Reddy on Apr 6th, 2009

Hi There, Thanks for this plug in, it was really cool. I am using it in my website under the music section to enable users to browse through the music folders. I have done some basic min modifications and it works like a charm. Thanks and keep up the good work

Pradeep on Apr 8th, 2009

[EN] (ASP): I asked for some partners in China to access the page in ASP without the "escape" function and worked perfectly. Now they can see the folders and files with spaces and special characters without any problem.

[PT] (ASP): Eu solicitei para alguns parceiros na China acessarem a página em ASP sem a função "escape" e funcionou perfeitamente. Agora eles podem ver as pastas e arquivos com espeços e caracteres especiais sem nenhum problema.

Virgulino on Apr 8th, 2009

Can someone please tell me why I am seeing a blank row appended to the folder contents everytime i click a folder?? Then when the folder collapses, it still shows that blank row under the collapsed folder.

Jason on Apr 10th, 2009

I've tried almost everything. I don't get any error, but files/folder are not displayed. Is there a setting in apache or php I have to set?

Can anyone help me further?
Thnx.

Btw, I use wampserver2, to test the website I'm building.

vito on Apr 14th, 2009

@vito: did you add the empty div? in your html?

<div id="container_id"></div>

BTW, if you use Firefox download Firebug. It will help a lot with js / jQuery errors.

Ramiro on Apr 14th, 2009

@Ramiro:

Thanks for the quick response. I added the div already.

I was reformatting my code, to paste it here in a readable state to get some of your input about it. However, after that reformatting it worked. No idea what it was, but it was probably getting in the way for proper execution of the code.

Something to keep in mind ;-)

vito on Apr 14th, 2009

I have a weird problem:
If I include the script on a page into my website, then the script gets in to a loop or something.
I have look at the page in google chrome I see that it opend the website over and over for every submap that there is.
I just can't figure out what is going wrong. It must me somekind of conflict with something else but what.. I dissabled the google custom search and google analytics code and that seems to help a little, but It still doesn't fix the problem.

The most weird thing is, that if I copy the source code of page, put that into a new blank html page and open it, then everything is working fine....

Hope that someone has an idea what is going wrong..

Ruud on Apr 16th, 2009

If I leave all the code in my webpage, so I don't disable google etc, then the page gets loaded, i see the root map and after that the page refreshes and I see only a blank page.
If I look at the source code, then I still see the normal code as it should be

Ruud on Apr 16th, 2009

I love what you've done.

I'd like to use this as a way to select both directory and file paths. Richard van Zon (2008-07-09) gave an answer above for how to return a directory click. What I'd like is almost that, but I'd like it to only return a directory on a double click. For a single click, I'd like the script to work just like it does by default. But if the user double clicks on the directory, I'd like it to return the directory path.

Any ideas on how I might be able to do that?

Thanks very much!

Christopher Werby on Apr 21st, 2009

Hi, I have a question: I need to put in the right side of the tree a button that adds a new folder inside the folder where the button is located, example : i have a folder called photos and have a button beside for add a new folder inside the photos folder, How I can do that??
Thanks!

Ruben Restrepo on Apr 22nd, 2009

Did somebody know how to pass from PHP to Javascript a string with the path for "root:"?

I need to have several trees in a web page, but don't want to hardcode every one with their path, instead of that I want to configure different paths and pull them from the web server to client when I need without the need of hardcode every path in every call.

Thanks in advance!

Martin Revert on Apr 23rd, 2009

I made a patch which adds the possibility to select a folder. Quite when you try to select just directories instead of files.
http://www.grasvezel.nl/Blog/view/193/jQuery_filetree_Patch.html

Utopia on Apr 23rd, 2009

This plugin doesn't work!!!!!!!!!!!!!!!!!

I followed the demo to a tee on both IIS and Apache servers. I can't get the folders and files to appear. It just doesn't work.


Oh wait....

THANKS, Cory S.N. LaViska!!!!!!!!!!!!!!!!!!!!

I found out my PHP4 wasn't compatible to use 'scandir'! That makes a HUGE difference.

I'll go back to see if I can get it to work in IIS.

Kujo on Apr 23rd, 2009

Great plugin.
How can I load tree with some dirs expanded by default?

Adam on Apr 25th, 2009

Is there any possibility to call something like method to expand some dirs without clicking on it? E.g. with clicking on external link?
ta

Adam on Apr 25th, 2009

Thank you ... this tutorial has me very helped.

Webagentur on Apr 29th, 2009

great plugin, just perfect for my project.

I've configured the plugin to open a new window and download a file after it's been clicked. I'm wondering if its possible to have the selected file appear on the same page within another div?

Even more tricky..

Can I get a gallery/slideshow plugin to display images from a file directory within my tree after it's been clicked?

much thanks,

d.

darius on Apr 30th, 2009

In case anyone else is having this error
"Undefined variable: root on line 21"

Go to your PHP.ini file and changed the value "display_errors = on" to "display_errors = (E_ALL ^ E_NOTICE)" , restart the server and everything should be working

Rich on May 3rd, 2009

Hello All,
I have downloaded the script and followed as mentioned in the usage, but I can't see anything. Its just displaying blank.
Any body please help me out.

Thanks in advance.

Arun on May 4th, 2009

I am having an issue with using this plugin. An empty text node is being added below each directory once I expand and collapse it. So, I am getting an additional space between each directory node. Please help me out....

sudheer on May 4th, 2009

might help someone to know that I had to add a trailing "/" to my root

root: '/files/'

renobird on May 6th, 2009

Alguien habla español aca:(, no puedo hacerlo andar. No podrian ayudarme con un ejemplo mas claro no me meustra el arbol.

Fernando on May 9th, 2009

How can I get the folder name and also full path of the folder when I click above any folder of this list view(like getting file path). Also after the clicking above the folder or file , the folder or file will be selected

please any body please help me out soon..

Susanta Samanta on May 12th, 2009

How can highlight the selected node??
please help me...

Sam on May 13th, 2009

Hello there,

I am having strange behavior with IE such that when the tree view is rendered it shows additional space between the folders and files. However this behavior is not shown on Firefox. I am using XSL as the connector script. Please provide me with the solution.
Thanks,
Girish

Girish on May 13th, 2009

I've been trying to create a function to open to a specific node. The theory seems like it should work but only the root node is opened. I think it's because the post hasn't completed before the next one is called. Anyone got any ideas?

function expandNodes(path)
{
var folders = path.split('\/');
path = '';
for (var item in folders)
{
path += folders[item] +'/';
if(folders[item]!='..')//ignore back path
{
console.log(item + ': ' +path);
current = $('#tree').find('li.directory a[rel=' + path + ']').css('font-weight','bold').click();
current.parent().removeClass('collapsed').addClass('expanded');
}
}
}

fruitbatinshades on May 15th, 2009

I've nearly got this working now. It finds the children but adds them to the wrong place. Seems to be a step out of sync.
Change the block around line 50ish

return $(this).each( function() { //fbis - added return
$this = $(this)
expandNodes=function(path)
{
var folders = path.split('\/');
path = '';
current = $('#tree').find('li.directory a[rel=' + path + ']');
for (var item in folders)
{
path += folders[item] +'/';
if(folders[item]!='..')//ignore back path
{
console.log(item + ': ' + path);
current = $('#tree').find('li.directory a[rel=' + path + ']');
current.css('font-weight','bold');
showTree( current, escape(current.attr('rel')));
current.parent().removeClass('collapsed').addClass('expanded');
}
}
};
var show = showTree();
// Loading message
$(this).html('<ul class="jqueryFileTree start"><li class="wait">' + o.loadMessage + '<li></ul>');
// Get the initial file list
showTree( $(this), escape(o.root) );
});


fruitbatinshades on May 15th, 2009

Would be nice if there's an example input and output to and from the script, just to understand what do we need to do when debuging it. Using firebug on the demo pages, doesn't reveal anything. Are we expected to download the existing scripts (connector), deploy them and fetch the info we need, to migrate it to another connector ?

Mansour on May 19th, 2009

Woops, sorry. Just saw the custom connector part. Apologies !

Mansour on May 19th, 2009

Hi Cory, this is excellent but I'm having some trouble getting it to work. It seems to work fine locally on my desktop with xampp installed but when I upload to my live server I get nothing.

Do I need to put in an absolute URL in the root? like 'www/htdocs/'?

Also I cannot figure out how to launch the documents instead of using a dialog popup.

Thanks!

Steve on May 19th, 2009

having trouble adding custom tooltips (qTip) to the items in the tree. any suggestions?

Gregg on May 19th, 2009

great work , but missing something i need which is when selecting a file to keep da background selected "blue"

so i edited the plugin in this why
1- h($(this).attr('rel'),this); .. jqueryFileTree.js Line 80
2-
$('#div_id').fileTree({
root: '/' ,
script: 'ajax.php',
folderEvent: 'click',
expandSpeed: 1,
collapseSpeed: 1
}, function(file,object) { $('a').css({'background':''}); $(object).css({'background':'#BBDDFF'});
});

helpfully some one find it useful ;)

khalil Majdalawi on May 20th, 2009

To use this script do all of the Dependencies have to be in the same root as the folders you want to drill into or can you look outside of the scripts root to drill into other directories using ../../otherfolder in the root var in the jqueryFileTreejs and then calling the specific folder on the page.html js 'thisfolder/'

good stuff btw thanks

gabe on May 22nd, 2009

Finally got auto expanding to work! The issue is that you need to turn async off as we need to wait until the last folder is loaded before we can load the next.

I've changed a load of stuff for my own use (added filters etc) so will have to upload it as a new project unless Cory wants to get in touch and do a merge!

Give me a yell if you're interested Cory.

fruitbatinshades on May 28th, 2009

Hello there,

Can any one please tell me why an extra space is shown between two folders or files? This happens only in case of IE while other browsers show perfectly.

Girish on May 29th, 2009

hi,
thanks for this great piece of jQuery!
for my personal use i needed to call a function whenever a directory-link gets clicked.
this way worked for me:
// adding the default value (line 48):
if( o.dirFunc == undefined ) o.dirFunc = null;

// calling the function in the "expand-part" of the script
if(o.dirFunc) {
eval(o.dirFunc + "('" + $(this).attr("rel") + "');");
}

// set the new option 'dirFunc' with function name
$('#element').fileTree({
root: '/home/',
dirFunc: 'myDirFunc',
}, function(file) {
alert(file);
});

cheerz
engine

engine on May 31st, 2009

@fruitbatinshades

I'm intrested in your script.
Please post it as soon as possible :-)

Stef on May 31st, 2009

Hi mate. Nice plugin, works well. Just want to point out a few things to people...

1) You can use whatever data source you want, whether it be a file system, database list, whatever, so long as your connector returns the correct html. Thats up to you, not the plugin developer.

2) The server side connector file can be anywhere in your web root. I usually put ajax files in /ajax. The directory in the samples is only an example.

3) Dont bother with a javascript link to download unless you really need it - just specify a web path to the file in the href attribute of the anchor for the file.

I have one question, Cory.. I have integrated the file tree browser in my framework, and also copied your demo page to my web server for testing, including the js files you are using for the demo. It works, except for the expandEasing function which never actually displays an animation - collapseEasing does! Im yet to figure out why it animates when hosted on your server and not another! No typos that I can see, correct variable syntax.. Im using an Apache server on Windows, with PHP5, but this also happens on our linux box. Im stumped!

Vertigo on Jun 3rd, 2009

I figured it out just after posting this - compared your sample php connector output to mine, I was lacking the display: none; on the initial ul. Adding this fixed the animations. Any idea why this is?

Vertigo on Jun 3rd, 2009

Did anyone tried to get it to work with the ruby connector by Erik Lax?

It requires some routes tweaking that I can't get to work.

its there any implementation sample/tut we can look at?

Bzouchir on Jun 3rd, 2009

@Vertigo - glad you figured it out. It happened because this selector:

$(c).find('UL:hidden').show(); else $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });

Wasn't matching anything when the elements were visible :)

Cory S.N. LaViska on Jun 3rd, 2009

Very nice !
A wonderful plugin ;)

mikaweb on Jun 4th, 2009

I figured how to use the script from fruitbatinshades as he posted it.

What do I mean: I added 'expandNodes('10'); setTimeout("expandNodes('26')",2000);
in the "expand" section of the 'click' event of the tree.
So now when i click one node of the tree, two nodes actually expand. (i removed the other code for expanding when clicking)

But this is a bit messy as you can see. How can I trigger the tree to expand from the javascript from my page ? As in, how can I call a method of the filetree ?

What does fruitbatinshades actually mean by 'turn async off' ?
I understood this as: wait for the tree to expand the node, and then expand the next one. That's why I uses the setTimeout(..);

Can someone explain me those things please ?

Stef on Jun 5th, 2009

great plugin!!!!
that is exactly what i want for a new project of mine.
thanks again. Cheers!!!

vijay joshi on Jun 6th, 2009

Hello Cory,

Thanks for the great plugin, We have used it in our project at Kodingen.com, an online development environment, I have slightly changed it, put drag and drop functionality and some extra fields etc...

And I mentioned about you and abeautifulsite.net on our credits page(also on screencast). I would like to hear your ideas about the site and implementation of your plugin.

Thanks again sharing this.
Sinan Yasar
Kodingen.com

Sinan Yasar on Jun 8th, 2009

its very appreciable effort by all the people involved, what i want to know is that is there any possibility that we can pass the path of folder as an argument ? so that whenever the page is accessed it shows the content of the path that has been passed as an argument

Umair Aslam on Jun 8th, 2009

Hi,

What's the easiest way to set the default open node?

I see in php_file_tree_query.js where it hides all with...

// Hide all subfolders at startup
$(".php-file-tree").find("UL").hide();

...but what if I want to open a node/folder by default maybe even use a parameter passed to the initial php?

Thanks anyone for any help... Steven

Steven Culshaw on Jun 9th, 2009

@Umair Aslam,

If i get your question correct, If you write the path of the file to an attribute on your <li> elements on filetree.php, you can get that value easily with jquery and then pass it to anywhere you want.

for example:

suppose you have the tree as
<ul><li class="directory" rel="my_folder_path">Foldername</li></ul>

then in your jquery,
$("li.directory").click(function(){
var my_folder_path = $(this).attr("rel");
my_function(my_folder_path);
})

or you can hijack the plugin, and on folderevent you can put your necessary data.

hope it helps...

Sinan Yasar on Jun 9th, 2009

I needed to extend the script to pass additional parameters to a connector.

To do this, add:

additionalParams: { a: 'b', foo: 'bar' }

to your call to the script.. and then modify jqueryFileTree.js to pass these params through to the post method:

--- original/jqueryFileTree.js 2008-05-13 18:56:00.000000000 +0100
+++ jqueryFileTree.js 2009-06-10 13:28:10.000000000 +0100
@@ -45,13 +45,17 @@
if( o.collapseEasing == undefined ) o.collapseEasing = null;
if( o.multiFolder == undefined ) o.multiFolder = true;
if( o.loadMessage == undefined ) o.loadMessage = 'Loading...';
-
+ if( o.additionalParams == undefined ) o.additionalParams = null;
$(this).each( function() {

function showTree(c, t) {
$(c).addClass('wait');
$(".jqueryFileTree.start").remove();
- $.post(o.script, { dir: t }, function(data) {
+
+ var params = { dir: t };
+ $.extend(params, o.additionalParams);
+
+ $.post(o.script, params, function(data) {
$(c).find('.start').html('');

Alex H on Jun 10th, 2009

There have been two other users who couldn't get anything loaded. One of them didn't get any answer. The other was told to add this line to his jqueryFileTree.php file:

$root = $_SERVER["DOCUMENT_ROOT"];

but didn't say if it worked for him or not.
When I added it it didn't do anything. Instead:

$root = $_SERVER["localhost"]; works

But I get the error:

Notice: Undefined index: localhost in jqueryFileTree.php on line 21 (the line I added)

It works, and it's still a lot better than not showing anything but I can't manage to get rid of the error. I'm surely doing something wrong. I haven't modified anything in the php file except adding this line of code. And I can bet it's something very simple. But I can't get my head around it.

Anyone please help :) Thank you in advance.

Paul on Jun 11th, 2009

Paul -- your server has error reporting configured to show development notices (the default in PHP 4 and 5 is to show only errors and warnings, not notices). Feel free to patch the code yourself, or see this page for more information about disabling that option:

http://us2.php.net/manual/en/errorfunc.configuration.php

Cory S.N. LaViska on Jun 11th, 2009

@Sinan Yasar

firstly thanx for your time. Actually i am using jsp as front end and i have a combo box displaying the local drives of a system and what i wanted was that the files/folders of the selected drive were displayed below. i only have begginer level knowledge of javascript and newbie to jQuery, if its possible to do so it wud b of great help to me

Umair Aslam on Jun 11th, 2009

artico: I couldnt get this tree working (I couldnt show any tree apart from the root directory files/folders) but I went to your link and got that one working perfectly (as it points straight to folder that its sat inside - just what i wanted!)

Thanks to both parties

applet on Jun 15th, 2009

Hello there,

I want to get the parent folder of the folder which is clicked. Can any one tell me how to get it?

Girish on Jun 19th, 2009

Are there any lines for this code, you know to visually identify the indent level of the item, I would like to be able to see them

Ben on Jun 21st, 2009

Hi, is it possible to hide file extensions when browsing the files? All the files will be .php

Thanks!

Alan on Jun 23rd, 2009

Hello there,

Is it possible to have callback function when the folder is collapsed. I mean we can define a call back function at the click of the folder. But I also want to have a function that gets executed when a folder is collapsed. Please share the code if it is possible.

Thanks

Girish on Jun 25th, 2009

Great component. I have used in an application not filed based and it works.
It's one of the simple and powerfull trees I have seen. Thank you!.

aaloy on Jun 25th, 2009

hope that it supports horizontal tree.

levin on Jun 26th, 2009

Have uploaded an revised edition of this plugin at http://plugins.jquery.com/project/filetree including drag'n'drop support, callbacks, etc...

Carl on Jun 26th, 2009

Great script. I'm having the same trouble as sudheer and Girish, however - IE on Windows Vista adds space between folders after collapsing. The files flash visible for a moment at the end of the collapse, then the space is left.

Rick Gladwin on Jul 1st, 2009

Add a comment

Name*

Email*

Never, ever sold or spammed :)

Homepage

Comment*

Sorry, plain text only :(