1.1.5 • Published 7 years ago

js-treeview v1.1.5

Weekly downloads
108
License
MIT
Repository
github
Last release
7 years ago

Vanilla JavaScript TreeView

Build Statusnpm version

A stupid, simple tree view written with vanilla JS. I needed a lightweight control that just displayed data in a tree form and out popped this. I wrote a post on my blog that goes into more depth.

Dependencies

None. I built this using only plain JavaScript so there's no external dependencies. Other than the CSS required for styling.

Example Usage

If used outside of NPM/require, it will attach a global TreeVew object to window. If done using NPM, then it can be included using require like everything else. To install it via NPM:

npm install js-treeview

HTML

<div id="tree"></div>

JavaScript

// NPM
var TreeView = require('js-treeview');

var tree = new TreeView([
    { name: 'Item 1', children: [] },
    { name: 'Item 2', expanded: true, children: [
            { name: 'Sub Item 1', children: [] },
            { name: 'Sub Item 2', children: [] }
        ]
    }
], 'tree');

Options

NameTypeDescription
dataarrayThe array of items to populate the tree with. Each item is required to have a name and a children array. An optional expanded option allows you to default the child to be expanded when created.
idstring|objectID of the DOM element, or the DOM element itself, to render the tree in.

Events

NameArgumentsDescription
expandtarget - The DOM node that initiated the expandleaves - Array of leaf DOM nodes under the targetFires when a leaf is expanded.
expandAllNo argumentsFires after the expandAll method is called.
collapsetarget - The DOM node that initiated the collapseleaves - Array of leaf DOM nodes under the targetFires when a leaf is collapsed.
collapseAllNo argumentsFires after the collapseAll method is called.
selecttarget - The DOM node selecteddata - Data node associated with the selected elementFires when a outermost leaf is selected. Contains data item of the leaf selected.

Usage

tree.on('select', function (e) {
    console.log(JSON.stringify(e));
});

CodePen Example

License

This plugin is available under the MIT license.