-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathscript.js
More file actions
77 lines (66 loc) · 2.94 KB
/
Copy pathscript.js
File metadata and controls
77 lines (66 loc) · 2.94 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
71
72
73
74
75
76
77
document.addEventListener('DOMContentLoaded', function() {
const searchInput = document.getElementById('search-input');
const searchResults = document.getElementById('search-results');
let index; // Lunr index will be stored here
let indexLoaded = false; // Flag to indicate if the index is loaded
// Display a loading message
searchResults.innerHTML = '<li>Loading search index...</li>';
// Load the search index from search_index.json
fetch('search_index.json')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
index = lunr.Index.load(data); // Load the index
indexLoaded = true; // Set the flag to true
searchResults.innerHTML = ''; // Clear loading message
console.log('Search index loaded successfully.');
})
.catch(error => {
console.error('Error loading search index:', error);
searchResults.innerHTML = '<li>Error loading search index. Please check the console.</li>';
});
// Function to perform the search
function performSearch(query) {
searchResults.innerHTML = ''; // Clear previous results
if (!indexLoaded) {
searchResults.innerHTML = '<li>Search index not loaded yet. Please wait.</li>';
return;
}
if (!query || query.length < 2) {
searchResults.innerHTML = '<li>Please enter at least 2 characters.</li>';
return;
}
const results = index.search(query); // Perform the search
if (results.length === 0) {
searchResults.innerHTML = '<li>No results found.</li>';
} else {
results.forEach(function(result) {
const listItem = document.createElement('li');
const link = document.createElement('a');
let href = result.ref;
let parts = href.split('/');
let filename = parts.pop();
let breadcrumbs = parts.join(' > ');
link.href = href; // URL from the index
link.textContent = `${breadcrumbs} > ${filename.replace('.html', '')}`;
link.addEventListener('click', function(event) {
event.preventDefault(); // Prevent default navigation
searchInput.value = ''; // Clear the search input
searchResults.innerHTML = ''; // Clear the search results
window.location.href = href; // Navigate to the link
});
listItem.appendChild(link);
searchResults.appendChild(listItem);
});
}
}
// Event listener for the search input
searchInput.addEventListener('input', function() {
const query = this.value.trim();
performSearch(query);
});
});