-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.js
67 lines (55 loc) · 1.96 KB
/
search.js
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
document.addEventListener('DOMContentLoaded', () => {
let pages = [];
fetch('/resources/pages/pages.json')
.then(response => {
if (!response.ok) {
throw new Error("Failed to load pages");
}
return response.json();
})
.then(json => {
pages = json;
})
.catch(error => {
console.error("Error loading pages:", error);
})
const searchInput = document.getElementById('searchinput');
const resultsContainer = document.getElementById('resultbox');
const NO_RESULTS_FOUND = '<h4 id="blankwarning">No results found.</h4>'
if (!searchInput || !resultsContainer) {
console.error('Required DOM elements are missing.');
return;
}
function searchWiki() {
const query = searchInput.value.trim();
resultsContainer.innerHTML = '';
if (!query) {
return;
}
const matches = pages
.filter(page =>
cleanTitle(page.title).includes(cleanTitle(query))
).sort(
function(a, b) { return cleanTitle(a.title).indexOf(query) - cleanTitle(b.title).indexOf(query)}
);
console.log(matches);
if (matches.length > 0) {
matches.forEach(match => {
const listItem = document.createElement('li');
listItem.className = 'result-item';
listItem.innerHTML = `
<a href="${match.url}" class="searchlink">${match.title}</a>
<p>${match.description}</p>
`;
resultsContainer.appendChild(listItem);
});
} else {
resultsContainer.innerHTML = NO_RESULTS_FOUND;
}
}
searchInput.addEventListener('input', () => {
searchWiki();
});
// lowercase, remove spaces, dashes
let cleanTitle = (title) => title.toLowerCase().replace(/[\s-]/g, "");
});