Last active
August 29, 2015 14:25
-
-
Save aleroddepaz/76889a9f1aa6cb7c0fd4 to your computer and use it in GitHub Desktop.
Pure JS Treeview, based on nested unordered lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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