3 ms·
LunrJS looks great, but if one needs an instant text-based search, this is what I've got on my FAQ page: function search(querybox, searchables, searchs
by ignoramous 6y ago
LunrJS looks great, but if one needs an instant text-based search, this is what I've got on my FAQ page:
function search(querybox, searchables, searchstatus) {
const t = querybox.value.toLowerCase()
let hits = [];
let misses = [];
for (s of searchables) {
// empty "t" matches everything
if (s.innerText.toLowerCase().indexOf(t) >= 0) {
hits.push(s)
} else {
misses.push(s)
}
}
if (hits.length > 0) {
for (g of misses) g.style.display = "none";
for (k of hits) k.style.display = ""; // default display style
searchstatus.innerText = hits.length + " results found."
} else {
searchstatus.innerText = "No results found."
for (g of misses) g.style.display = "" // show all
}
}
function setupSearch() {
const searchables = document.getElementsByClassName("searchme")
const querybox = document.getElementById("searchbox") // <input>
const searchstatus = document.getElementById("searchstatus")
if (!searchables || !querybox || !searchstatus) {
console.log("search setup skipped")
return
}
querybox.addEventListener("keyup", e => search(querybox, searchables, searchstatus), false)
}
window.addEventListener('load', function(event) {
setupSearch();
}, false)
- m-i-l 6y agoLooks nice, but as you say that just searches the current page. Here's how I search my entire site with slightly fewer lines of JavaScript: // Construct the API query const apiEndpoint = 'https://searchmysite.net/api/v1/search/michael-lewis.com'; let urlParams = new URLSearchParams(window.location.search); let queryParam = urlParams.get('q'); if (queryParam == null || queryParam == '') { queryParam = '*' } let apiQuery = apiEndpoint.concat('?q=', queryParam); // Build the results (using fetch rather than XMLHttpRequest) fetch(apiQuery) .then((resp) => resp.json()) .then(function(data) { let searchResults = data.results; document.getElementById('query').value = queryParam; // Set the value of the search box to the query if (searchResults && searchResults.length > 0) { return searchResults.map(function(result) { // Each result is going to be displayed as <li><a href="${result.url}" class="title">${result.title}</a></li> let li = document.createElement('li'), a = document.createElement('a'); a.appendChild(document.createTextNode(`${result.title}`)); a.href = `${result.url}`; a.classList.add('title'); li.appendChild(a); // Each result is added to the <ul id="results"></ul> document.getElementById('results').appendChild(li); }) } else { // If there are no results update the <h1 class="title" id="results-title">Results</h1> document.getElementById('results-title').innerText = 'No results'; } }) .catch(function(error) { console.log(error); });