Telerik blogs
Kendo UI Treeview

Take the hierarchical TreeView component further by learning how to programmatically add and delete items and associated actions from a TreeView instance.

In the last post covering the TreeView (Part 1), you learned the basics of creating a TreeView component. In today's episode, we will continue building on our bookmark example to practice more advanced skills. Specifically, you will learn how to add and remove bookmark items from the TreeView. Doing so will allow you to explore several of the methods available to the TreeView API. We will also incorporate a couple of the components we have learned about before. This will be the final test to determine if you have mastered control over the Kendo UI navigation components. This is a preview of what we will be building:

Kendo Ui Treeview Component Example

Adding Items to the TreeView

To add items to our bookmark, we will use an input field to enter the text and a button that will append the item to the currently selected folder when clicked. For this example, we will be adding files to folders. Therefore, only nodes that have child items can have additional items added to them. To achieve this we will need to do the following:

  1. Create an instance of the TreeView
  2. Use the TreeView instance to get the selected node
  3. Create a Kendo UI button with a click event listener
  4. Write the function to append the item to the selected node

The first step is to create a TreeView instance and store it in a variable. This will allow us to use the TreeView’s methods for other operations. Add this line after your code for initializing the tree:

const tree = $("#tree").data("kendoTreeView");

In the second step, we will add a select event to the TreeView’s configuration. We will create an event handler onSelect that will update our reference to the currently selected item. This is the code we have so far:

$('#tree').kendoTreeView({
  ...
  select: onSelect 
});

const tree = $("#tree").data("kendoTreeView");
let selected;

function onSelect(e){
  selected = tree.dataItem(e.node);
}

The dataItem method takes an HTML element as a parameter and returns a model of its data. We do this step so that we can access the node’s properties like text and ID.

The third step is to create the button and attach an event handler to it. The markup for the button and input field will be placed above the markup for the tree. The code to initialize the Kendo UI button will go right before the initialization code for your tree. This is the code we will add:

<div>
  <input type="text" id="input" class="k-textbox">
  <button id="button" class="k-primary" >Add Folder</button>
</div>

$('#button').kendoButton({
  click: addNode
});

The last step is to create the addNode function. We can use the append method of the TreeView to add an item to the list of bookmarks. The method requires the data of the new node and the parent node it will be appended to. This is the implementation:

function addNode(){
  if (selected.hasChildren) {
    const value = $('#input').val();
    const node = tree.findByUid(selected.uid);
    tree.append({text: value, icon:'fa fa-file'}, node);
  }
}

We use the method tree.findByUid to convert our model back to a node. This method is one way to find a node in a TreeView. You could also use findByText and pass it the value selected.text.

Removing Items from the TreeView

Next, we will take a different approach to remove a bookmark. When we right-click on an item, we want a menu to appear with a delete option. When delete is selected, it will remove the item. If the item is a folder, it will remove the folder with all of its children. If you recall from a previous lesson, we can create such a menu with the Kendo UI context menu component. These are the steps we will take to add the new functionality:

  1. Create a Kendo UI context menu
  2. Add a select event to the context menu
  3. Create the function to delete a node

First, to create the context menu we have to add the HTML to our page and initialize it with the kendoContextMenu method. This is the markup and code that will be added:

<ul id="context"></ul>

$('#context').kendoContextMenu({
  target: '#tree',
  filter: '.k-item',
  dataSource: [
    { text: 'delete' }
  ],
  select: deleteNode
});

The target option specifies the context. The filter option allows us to target individual nodes in our TreeView. The k-item class is the name used on all of the nodes. When we right-click on one of the nodes, we will be able to identify the specific node through the select event. The select event triggers when you select an item from the context menu.

Last, is the is the implementation for deleteNode:

function deleteNode(e) {
  tree.remove(e.target);
}

Inside of the deleteNode function, we use e.target to identify the node that was right-clicked on. Putting it all together, we have this:

<body>
  <div>
    <input type="text" id="input" class="k-textbox">
    <button id="button" class="k-primary">Add File</button>
  </div>
  <ul id="tree"></ul>
  <ul id="context"></ul>
  <script>
    $(document).ready(function() {
      $('#button').kendoButton({
        click: addNode
      });

      $('#context').kendoContextMenu({
        target:'#tree',
        filter: '.k-item',
        dataSource: [
          {text: 'delete'}
        ],
        select: deleteNode
      });

      $('#tree').kendoTreeView({
        template: '#= item.text #',
        dataSpriteCssClassField: 'icon',
        dataSource: [
          {text: 'Bookmarks', icon:'fa fa-folder', items: [
          {text: 'tech', icon:'fa fa-folder', items: [
              {text: 'tutorials', icon:'fa fa-file'},
              {text: 'blogs', icon:'fa fa-file'}
          ]},
          {text: 'work', icon:'fa fa-file'}
          ]}
        ],
        select: onSelect
      });

      const tree = $("#tree").data("kendoTreeView");
      let selected;

      function onSelect(e){
        console.log(e);
        selected = tree.dataItem(e.node);
        console.log(selected);
      }

      function addNode(){
        if (selected.hasChildren) {
          const value = $('#input').val();
          const node = tree.findByUid(selected.uid);
          tree.append({text: value, icon:'fa fa-file'}, node);
        }
      }

      function deleteNode(e) {
        tree.remove(e.target);
      }
    });
  </script>
</body>

Coming Up - Tooltip, Splitter and Window

If you have come this far, well done. You are ready to graduate to the next level. In the next series of lessons, you will master the tooltip, the splitter, and the window component. The tooltip is a popup that appears near an item when you mouseover or click it. It is a common item you encounter, but the splitter and the window are not so common. This makes them extra special to acquire. The splitter lets you divide your screen into resizable panes. The window component is a modal with the controls of a typical window. With these components and the others to come, you will be equipped to build the next chat app, code sharing site, or whatever else you imagine. The more tools you acquire, the more you will be able to build, so code on!

Try Out the TreeView for Yourself

Want to start taking advantage of the Kendo UI TreeView, or any of the other 70+ ready-made Kendo UI components, like Grid or Scheduler? You can begin a free trial of Kendo UI today and start developing your apps faster.

Start My Kendo UI Trial

Angular, React, and Vue Components

Looking for UI component to support specific frameworks? Check out the TreeView For Angular, TreeView for React , or Treeview for Vue.

Resources


Alberta Williams
About the Author

Alberta Williams

Alberta is a software developer and writer from New Orleans. Learn more about Alberta at github.com/albertaw.

Related Posts

Comments

Comments are disabled in preview mode.