-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsearch.js
More file actions
70 lines (62 loc) · 2.55 KB
/
search.js
File metadata and controls
70 lines (62 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
export default class Search {
constructor(searchInputId) {
console.log('In search ctor.')
this.searchInputId = searchInputId;
const searchInputControl = document.getElementById(searchInputId);
if (!!searchInputControl) {
searchInputControl.addEventListener('input', (e) => {
console.log('event:' + e.target.value);
if (!!e && !!e.target && !!e.target.value) {
this.search(e.target.value);
return;
}
this.clearSearch();
});
}
}
search = (keyword) => {
console.log(`Search for keyword: ${keyword}`);
// Restore
this.clearSearch();
// Hide items that has no match
const targetTags = document.getElementsByClassName('searchable-item');
if (!!targetTags) {
const foundTagLength = targetTags.length;
for (let i = 0; i < foundTagLength; i++) {
targetTags[i].removeAttribute('style');
if (targetTags[i].innerText.toLowerCase().indexOf(keyword.toLowerCase()) < 0) {
targetTags[i].style.display = "none";
}
}
}
// Post process sections that doesn't have any item
const ulTags = document.getElementsByTagName('ul');
if (!!ulTags && ulTags.length > 0) {
const ulTagCount = ulTags.length;
for (let i = 0; i < ulTagCount; i++) {
const ulTag = ulTags[i];
if (!ulTag.innerText) {
const noItemPlaceHolder = document.createElement('li');
noItemPlaceHolder.setAttribute('class', 'no-item-placeholder');
noItemPlaceHolder.innerText = "No match.";
ulTag.appendChild(noItemPlaceHolder);
}
}
}
};
clearSearch = () => {
console.log('Clear search!');
const targetTags = document.getElementsByClassName('searchable-item');
const foundTagLength = targetTags.length;
for (let i = 0; i < foundTagLength; i++) {
targetTags[i].removeAttribute('style');
}
const noItemPlaceHolders = document.getElementsByClassName('no-item-placeholder');
if (!!noItemPlaceHolders && noItemPlaceHolders.length > 0) {
const noItemPlaceHolderLength = noItemPlaceHolders.length;
for (let i = noItemPlaceHolderLength - 1; i >= 0; i--) {
noItemPlaceHolders[i].remove();
}
}
}
}