
A simple, SEO-friendly jQuery tree plugin which converts nested HTML lists into a collapsible and expandable tree structure. Ideal for representing your folders, files, menu items as a hierarchical tree.
More features:
- Custom collapse all & expand all buttons.
- Auto saves the current state using localStorage or sessionStorge.
How to use it:
1. Install & download.
# NPM $ npm install @kanety/jquery-simple-tree --save
2. Link to jQuery library and the jQuery simple tree plugin's files.
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <link rel="stylesheet" href="dist/jquery-simple-tree.css"> <script src="dist/jquery-simple-tree.js"></script>
3. Add node ID to list items using the data-node-id
attribute:
<ul id="basic"> <li data-node-id="1"> <span>1</span> <ul> <li data-node-id="1.1"> <span>1.1</span> <ul> <li data-node-id="1.1.1"> <span>1.1.1</span> </li> <li data-node-id="1.1.2"> <span>1.1.2</span> </li> </ul> </li> <li data-node-id="1.2"> <span>1.2</span> <ul> <li data-node-id="1.2.1"> <span>1.2.1</span> </li> <li data-node-id="1.2.2"> <span>1.2.2</span> </li> </ul> </li> </ul> </li> <li data-node-id="2"> <span>2</span> <ul> <li data-node-id="2.1"> <span>2.1</span> </li> <li data-node-id="2.2"> <span>2.2</span> </li> </ul> </li> </ul>
4. Call the plugin to initialize the tree.
$('#basic').simpleTree();
5. Expand/collapse all nodes using toggle buttons:
<button type="button" id="expander">expand</button> <button type="button" id="collapser">collapse</button>
$('#basic').simpleTree({ expander: $('#expander'), collapser: $('#collapser') });
6. Determine whether to save the current open/close states using localStorage or sessionStorge.
$('#basic').simpleTree({ storeState: true, storeType: 'session' // or 'local' });
7. Specify the nodes to open on init. Default: all.
$('#basic').simpleTree({ opened: [1, 1.1] });
8. Get the opened/closed nodes.
$('#basic').simpleTree().on('node:open', function(e, $node) { var nodeID = $node.data('node-id'); $('#message').append("opened " + nodeID + " "); if ($node.data('node-lazy')) { $node.data('node-lazy', false); var newID = nodeID + '.1'; var loaded = '<ul><li data-node-id="' + newID + '" data-node-lazy="true"><span>' + newID + '</span></li></ul>'; $node.append(loaded); $('#callback').data('simple-tree').build(); } }).on('node:close', function(e, $node) { var nodeID = $node.data('node-id'); $('#message').append("closed " + nodeID + " "); });
This awesome jQuery plugin is developed by kanety. For more Advanced Usages, please check the demo page or visit the official website.
- Publication date: 25.01.2019
- Source