UNPKG

3.63 kBJavaScriptView Raw
1
2var searchAttr = 'data-search-mode';
3function contains(a,m){
4 return (a.textContent || a.innerText || "").toUpperCase().indexOf(m) !== -1;
5};
6
7//on search
8document.getElementById("nav-search").addEventListener("keyup", function(event) {
9 var search = this.value.toUpperCase();
10
11 if (!search) {
12 //no search, show all results
13 document.documentElement.removeAttribute(searchAttr);
14
15 document.querySelectorAll("nav > ul > li:not(.level-hide)").forEach(function(elem) {
16 elem.style.display = "block";
17 });
18
19 if (typeof hideAllButCurrent === "function"){
20 //let's do what ever collapse wants to do
21 hideAllButCurrent();
22 } else {
23 //menu by default should be opened
24 document.querySelectorAll("nav > ul > li > ul li").forEach(function(elem) {
25 elem.style.display = "block";
26 });
27 }
28 } else {
29 //we are searching
30 document.documentElement.setAttribute(searchAttr, '');
31
32 //show all parents
33 document.querySelectorAll("nav > ul > li").forEach(function(elem) {
34 elem.style.display = "block";
35 });
36 document.querySelectorAll("nav > ul").forEach(function(elem) {
37 elem.style.display = "block";
38 });
39 //hide all results
40 document.querySelectorAll("nav > ul > li > ul li").forEach(function(elem) {
41 elem.style.display = "none";
42 });
43 //show results matching filter
44 document.querySelectorAll("nav > ul > li > ul a").forEach(function(elem) {
45 if (!contains(elem.parentNode, search)) {
46 return;
47 }
48 elem.parentNode.style.display = "block";
49 });
50 //hide parents without children
51 document.querySelectorAll("nav > ul > li").forEach(function(parent) {
52 var countSearchA = 0;
53 parent.querySelectorAll("a").forEach(function(elem) {
54 if (contains(elem, search)) {
55 countSearchA++;
56 }
57 });
58
59 var countUl = 0;
60 var countUlVisible = 0;
61 parent.querySelectorAll("ul").forEach(function(ulP) {
62 // count all elements that match the search
63 if (contains(ulP, search)) {
64 countUl++;
65 }
66
67 // count all visible elements
68 var children = ulP.children
69 for (i=0; i<children.length; i++) {
70 var elem = children[i];
71 if (elem.style.display != "none") {
72 countUlVisible++;
73 }
74 }
75 });
76
77 if (countSearchA == 0 && countUl === 0){
78 //has no child at all and does not contain text
79 parent.style.display = "none";
80 } else if(countSearchA == 0 && countUlVisible == 0){
81 //has no visible child and does not contain text
82 parent.style.display = "none";
83 }
84 });
85 document.querySelectorAll("nav > ul.collapse_top").forEach(function(parent) {
86 var countVisible = 0;
87 parent.querySelectorAll("li").forEach(function(elem) {
88 if (elem.style.display !== "none") {
89 countVisible++;
90 }
91 });
92
93 if (countVisible == 0) {
94 //has no child at all and does not contain text
95 parent.style.display = "none";
96 }
97 });
98 }
99});
\No newline at end of file