Search
<script type="text/javascript" src="/assets/scripts/fetch.js">
<script type="text/javascript">
const endpoint = '/assets/search.json';
const pages = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data => pages.push(...data))
function findResults(termToMatch, pages) {
return pages.filter(item => {
const regex = new RegExp(termToMatch, 'gi');
return item.title.match(regex) || item.content.match(regex);
});
}
function displayResults() {
const resultsArray = findResults(this.value, pages);
const html = resultsArray.map(item => {
return `
${item.excerpt}
`;
}).join('');
if ((resultsArray.length == 0) || (this.value == '')) {
resultsList.innerHTML = `Sorry, nothing was found
`;
} else {
resultsList.innerHTML = html;
}
}
const field = document.querySelector('#search');
const resultsList = document.querySelector('#list');
field.addEventListener('keyup', displayResults);
field.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault();
}
});