The below javaScript code is converting the input paths in tree structure. That is working fine. But I have one issue in that.
When the tree is too big that time if I am going to expand the bottom list items, after every click on the "+" button is taking me to the top of the web page rather than focusing on the child items that I have expanded.
What I have tried:
<pre lang="Javascript">
var convert = function(input) {
var output = {};
input.forEach(function(path) {
var folders = path.split("\\");
var parent = output;
folders.forEach(function(f) {
parent[f] = parent[f] || {};
parent = parent[f];
});
});
return (output);
}
var drawFolders = function(input) {
var output = "<ul class='tree'>";
var counter = 0;
Object.keys(input).forEach(function(k) {
if (((k.length) > 0) && Object.keys(input[k]).length) {
output += "<li><a href='#'>" + k;
} else {
output += "<li>" + k;
}
if (Object.keys(input[k]).length) {
output += drawFolders(input[k]);
}
if (counter == 0) {
output += "</a></li>";
} else {
output += "</li>";
}
counter = counter+1;
});
output += "</ul>";
return output;
}
var input = [
"A\\A1\\A2\\A3",
"A\\B\\B1\\B2",
"A\\B\\B4\\B5\\B5",
"A\\C\\C1\\C2\\D5",
"A\\D\\C1\\C2\\D5",
"A\\E\\C1\\C2\\D5",
"A\\F\\C1\\C2\\D5",
"A\\G\\C1\\C2\\D5",
"A\\H\\C1\\C2\\D5",
"A\\I\\C1\\C2\\D5",
"A\\J\\C1\\C2\\D5",
"A\\K\\E2\\C2\\D5",
"A\\K\\C1\\C2\\D5",
"A\\L\\C1\\C2\\D5",
"A\\M\\C1\\C2\\D5",
"A\\N\\C1\\C2\\D5",
"A\\O\\C1\\C2\\D5",
"A\\P\\C1\\C2\\D5",
"A\\Q\\C1\\C2\\D5",
"A\\R\\C1\\C2\\D5",
"A\\S\\C1\\C2\\D5",
];
document.getElementById("output").innerHTML = drawFolders(convert(input));
var tree = document.querySelectorAll('ul.tree a:not(:last-child)');
for(var i = 0; i < tree.length; i++){
tree[i].addEventListener('click', function(e) {
var parent = e.target.parentElement;
var classList = parent.classList;
if(classList.contains("open")) {
classList.remove('open');
var opensubs = parent.querySelectorAll(':scope .open');
for(var i = 0; i < opensubs.length; i++){
opensubs[i].classList.remove('open');
}
} else {
classList.add('open');
}
});
}
ul.tree li {
list-style-type: none;
position: relative;
}
ul.tree li ul {
display: none;
}
ul.tree li.open > ul {
display: block;
}
ul.tree li a {
color: black;
text-decoration: none;
}
ul.tree li a:before {
height: 1em;
padding:0 .1em;
font-size: .8em;
display: block;
position: absolute;
left: -1.3em;
top: .2em;
}
ul.tree li > a:not(:last-child):before {
content: '+';
}
ul.tree li.open > a:not(:last-child):before {
content: '-';
}
<div id="output"></div>