How to Trees in jQuery

Often there are tasks in which you want to display the tree structure of the relationship of any entities. For example, navigation on the file system, site menu or textbook content.
image
The easiest option to display the tree structure in HTML is lists. But we are interested in trees with dynamic properties. You can’t do without javascript here. Since the solution is usually fast, using jQuery allows you to create dynamic trees, saving a decent amount of coding time. To save yourself a ton of time, go to the search engine and look for a suitable solution. In general, the creation of a tree on the site is often the only thing that is limited, but there are situations when the tree is suitable, but does not have any small chip, and there is nothing left to do but modify the existing tree.


Today, we have two trees on the preparation table: Treeview and jQuery File Tree .

For Treeview, you need to correctly add new nodes to the tree. On the one hand, it may seem that the task is strange, because the tree has the ability to add new nodes through the add selector. Like this:

var tree = $(".selector").treeview();
$(".button").click(function() {
 var newSublist = $("
  • New Sublist
      " +
         "
    • Item1
    • " +
         "
    • Item2
  • ").appendTo(tree);
     tree.treeview({
      add: newSublist
     });
    });


    But this approach has a drawback, a node can be added either to the end of the tree, or only to a strictly defined subnode. But what would a new node be added to the selected sub-site is apparently not easy to do, because the search for positive results, different from those described in the documentation, did not.

    Therefore, we apply the method of external intervention in the behavior of the tree:

    $(function() {
      var pervios_node; //запоминаем предыдущй выбранный узел
      $("#browser").treeview({
        toggle: function() {//когда дерево раскрыввается или сворачивается
          $(this).addClass("selector"); //добавляем свой класс
        //проверяем есть ли предыдущий узел и не равен ли он текущему (пару раз кликнули)
          if (pervios_node!=undefined && pervios_node!=this) {
                                //удаляем свой класс из предыдущего узла
            $(pervios_node).removeClass("selector");
          };
          pervios_node=this;
        }
      });
      $("#add").click(function() {
        //добавление узла в выбранный текущий узел
        var branches = $("
  • New Sublist
    • Item2
  • ").appendTo("li.selector ul:first");
        $("#browser").treeview({
          add: branches
        });
      });
    });


    The key point of the intervention is appendTo (“li.selector ul: first”) . We added a selector class to mark the currently selected node and now we can find it and add new nodes.

    The second tree is intended to display the file system structure. But he has one small flaw. If you disable file display in the connector, leave only directories, then you cannot view the contents of the horse folder.

    To solve this problem, you need to change the tree itself, for one fix a small error that is present in the original script.

    Let's get started. Let's move on to the jqueryFileTree.js tree script, and after setting the default values ​​for the tree options, add the line:

    var show_root=1; //true

    Below in the iterator function, we will fix the transfer of parameters in the POST request by adding the missing root parameter (now the connector will not swear at the missing variable), in the current version we make this parameter an empty string, because he participates in the formation of paths in the connector. And finally, we add the parameter regulating the addition of the root node to the tree - showroot.

    $.post(o.script, { dir: t, root: '',showroot:show_root }, function(data) {

    });
    show_root=0; //false

    After the function, we reset the parameter for adding the root node to the tree so that it does not appear in subnodes.
    The final touch will be a change in the connector.

    $_POST['dir'] = urldecode($_POST['dir']);
    $root= urldecode($_POST['root']);
    $show_root=(bool)urldecode($_POST['showroot']);

    if( file_exists($root . $_POST['dir']) ) {
      $files = scandir($root . $_POST['dir']);
      natcasesort($files);
      if( count($files) > 2 ) { /* The 2 accounts for . and .. */
        echo "
      ";
          //показываем корневую дирректорию
          if($show_root)
          {
            echo "
    • root
    • ";      
          }
          else
          {
            // All dirs
            foreach( $files as $file ) {
              if( file_exists($root . $_POST['dir'] . $file) &&
                      $file != '.' &&
                      $file != '..' &&
                      is_dir($root . $_POST['dir'] . $file) ) {
                echo "
    • " . htmlentities($file) . "
    • ";
              }
            }      
            // All files    
          }
          echo "
    ";  
      }
    }


    Thus, we have a root directory, from which the rest are already visible as subnodes of the tree.

    UPD:

    Demo of working with trees can be seen here .

    Also popular now: