Skip to content

Instantly share code, notes, and snippets.

@aleroddepaz
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleroddepaz/76889a9f1aa6cb7c0fd4 to your computer and use it in GitHub Desktop.
Save aleroddepaz/76889a9f1aa6cb7c0fd4 to your computer and use it in GitHub Desktop.
Pure JS Treeview, based on nested unordered lists
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<style>
.treeview ul {
padding-left: 24px;
list-style-type: none;
}
.treeview li > div {
cursor: pointer;
}
.treeview li > div:hover {
color: #33f;
}
</style>
<script src="script.js"></script>
</head>
<body>
<div class="treeview"></div>
</body>
</html>
(function() {
'use strict';
/**
* Creates a tree of nested list items from the parent node,
* based on the object's content.
*
* @param {any} parent - selector (or jQuery) of the parent node
* @param {object} data - object with the tree's data
*/
function tree(parent, data) {
if(typeof data === 'object') {
var wrapper = $('<ul/>').appendTo(parent);
$.each(data, function(node, children) {
var elem = $('<li/>').append($('<div/>').text(node)).appendTo(wrapper);
tree(elem, children);
});
}
}
var mydata = {
"Food": {
"Fruit": {
"Red": {
"Cherry": false
}
},
"Meat": {
"Beef": false,
"Pork": false
}
},
"Drink": false
};
$(function() {
tree('.treeview', mydata);
$('.treeview li:has(li)').css('listStyleType', 'square');
$('.treeview li > div').click(function() {
$(this).next().slideToggle('fast');
});
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment