Created
February 26, 2024 00:58
-
-
Save lonelydev/29393544f7955bc49f2f61afe0ad0413 to your computer and use it in GitHub Desktop.
Hugo-PaperMod optimised search using fusejs in fastsearch.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// add this snippet to your version of the fastsearch.js | |
// I copied the Hugo-PaperMod's fastsearch.js to my local assets/js/ | |
// then added the following code to trigger search after a 600ms delay | |
// I also listen to the input event | |
function debounce(fn, delay = 600){ | |
let timeoutId; | |
// fn could be invoked with more than one argument | |
return function(...arg){ | |
if (timeoutId) { | |
clearTimeout(timeoutId); | |
} | |
// execute fn after the timer expires (time in milliseconds) | |
timeoutId = setTimeout(function(){ | |
// use apply to invoke function with more than one arguments | |
// null is the object | |
fn.apply(null, arg); | |
}, delay); | |
}; | |
}; | |
/* This is the search trigger */ | |
function startSearch(e) { | |
try { | |
// run a search query (for "term") every time a letter is typed | |
// in the search box | |
if (fuse) { | |
// the actual query being run using fuse.js | |
const results = fuse.search(sInput.value.trim()); | |
if (results.length !== 0) { | |
// build our html if result exists | |
let resultSet = ''; // our results bucket | |
for (let item in results) { | |
resultSet += `<li class="post-entry"><header class="entry-header">${results[item].item.title} »</header>` + | |
`<a href="${results[item].item.permalink}" aria-label="${results[item].item.title}"></a></li>` | |
} | |
resList.innerHTML = resultSet; | |
resultsAvailable = true; | |
first = resList.firstChild; | |
last = resList.lastChild; | |
} else { | |
resultsAvailable = false; | |
resList.innerHTML = ''; | |
} | |
} | |
} catch(er){ | |
console.error("Search encountered an error!", er); | |
} | |
}; | |
//execute search as each character is typed | |
sInput.addEventListener("input", debounce(startSearch, e)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment