JavaScript Treeview with Search

JavaScript Treeview with Search
Code Snippet:folders tree pure javascript
Author: Timofte Alexandru
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 5,558
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create treeview navigation with a search box. It gets JSON format data and renders a filterable treeview dynamically. Moreover, it displays base64-based icons for files and folders/directories.

How to Create JavaScript Treeview with Search

1. First of all, create the HTML structure for the treeview as follows:

<div  class="container">
   <div class='widget'>
      <input placeholder="filter..." id="filterInput" oninput="solve()" type="text"/>
      <div id="folders"></div>
   </div>
</div>

2. After that, style the treeview navigation using the following CSS styles.

body {
  margin-top: 20px;
  background-color: #ECEFF1;
}

.widget {
  padding: 18px;
  background-color: #fff;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.12), 0 1px 4px rgba(0, 0, 0, 0.24);
}

.widget > input { 
    display: block;
    width: 100%;
    min-height: 30px;
    margin-bottom: 20px;
    border: 0 none;
    border-bottom: 1px solid #ccc;
    outline: none;
  }

.folder-container {
  margin: 10px;
  padding: 0 20px;
  margin: 0;
}

.folder-wrapper {
  margin: 0;
  padding: 0;

  list-style-type: none;
}

.file-item,
.folder-item {
  margin-left: -16px;
  padding-left: 20px;

  list-style-type: none;
}

.file-item {
  background: transparent  url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAsUlEQVQ4T2NkgIKE2q4DMDZW+j+jAgPj//0LmssSkeUZEQZ0/1/QXArnoxuSUNPdwMDIEMDwn2HDgpbSBpg8aQYw/H/PwMCQwMDIMHFBc9kCkCGkGODAwMAAwiBd9TDXYhiQUNtdwPCfgR97ePy7uKClfENCLcK7RLsA2UC8BoADi4HhP44YObigpfTAsHfBgMcC3vwAzze0TAcUuKDrAMN/RlwJCNVcRoaPC5pLA0CCALOMnRHTr6OKAAAAAElFTkSuQmCC') no-repeat left center;
}

.folder-item {
  font-weight: bold;
  background: transparent  url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA6UlEQVQ4T62TvQ3CMBCF31OgDxPACGwATAAjeAOgSKpECgoCiRTABmYDNgA2yAawAUpNwiGHH0GBlATcuPH3vbPvTPy4+COPXKCCpY30sgORPIU6dLtF5FTeYgWgA2KtQ1fnQj8amQ2C81fJVcZ65sZUfhTr0GmrYN5iZjWLpIqwC0oLVjah8hd7WPUBsvQIwC4ieD9zFwgDELuyMCCHuwDcAliWFgg2jwoQgxxWEDzeICfZqSDoPa9QHjZpVq1B5UUnEIXa91GhSKKnrm3mQEqXngNyMNNqBKYD/QqSsQ6d1X8+U4X0F3IDjRRPOikDqHUAAAAASUVORK5CYII=') no-repeat left center;
}

3. Finally, functionalize the treeview navigation with JavaScript.

const folders =
  {
    type: 'dir',
    name: 'app',
    children: [
      {
        type: 'file',
        name: 'index.html'
      },
      {
        type: 'dir',
        name: 'js',
        children: [
          {
            type: 'file',
            name: 'main.js'
          },
          {
            type: 'file',
            name: 'app.js'
          },
          {
            type: 'file',
            name: 'misc.js'
          },
          {
            type: 'dir',
            name: 'vendor',
            children: [
              {
                type: 'file',
                name: 'jquery.js'
              },
              {
                type: 'file',
                name: 'underscore.js'
              }
            ]
          }
        ]
      },
      {
        type: 'dir',
        name: 'css',
        children: [
          {
            type: 'file',
            name: 'reset.css'
          },
          {
            type: 'file',
            name: 'main.css'
          }
        ]
      }
    ]
  };

function displayJsonTree( data) {
  var htmlRetStr = "<ul class='folder-container'>";
  for (var key in data) {
    if (typeof(data[key])== 'object' && data[key] != null) {
      htmlRetStr += displayJsonTree( data[key] );
      htmlRetStr += '</ul></li>';
    } else if(data[key]=='dir'){
      htmlRetStr += "<li class='folder-item'>" + data["name"]+"</li><li class='folder-wrapper'>";
    }
    else if( key=='name' && data['type']!='dir' ){
      htmlRetStr += "<li class='file-item'>" + data['name']+"</li>";
    }
  }
  return( htmlRetStr );
}
function filterJson(data,string) {
  arr = [];
  for (var key in data)
    if (typeof(data[key]) == 'object' && data[key] != null) {
      if (data['name'].indexOf(string) <= -1) {
        for (var i = 0; i < data.children.length; i++) {
          arr=arr.concat(filterJson(data.children[i], string));
        }
        return arr;
      }
    }
    else {
        if (data['name'].indexOf(string) > -1) {
          arr = arr.concat(data);
          return arr;
        }
    }
}
document.getElementById("folders").innerHTML= displayJsonTree(folders);
function solve() {
  var toSearch=document.getElementById('filterInput').value;
  if(toSearch.length==0){
    document.getElementById("folders").innerHTML= displayJsonTree(folders);
  }
  else {
    var str = "Searching for: " + document.getElementById('filterInput').value + "\n";
    document.getElementById("folders").innerHTML = str + displayJsonTree(filterJson(folders, document.getElementById('filterInput').value));
  }
}

That’s all! hopefully, you have successfully integrated this JavaScript treeview navigation into your project. If you have any questions or facing any issues, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...