Skip to content

Instantly share code, notes, and snippets.

@rebelchris
Created June 15, 2021 06:22
Show Gist options
  • Save rebelchris/f252a845dc4a4a4d66ca707ad3f5b0c5 to your computer and use it in GitHub Desktop.
Save rebelchris/f252a845dc4a4a4d66ca707ad3f5b0c5 to your computer and use it in GitHub Desktop.
Static website search
document.addEventListener('DOMContentLoaded', function(event) {
const search = document.getElementById('search');
const results = document.getElementById('results');
let data = [];
let search_term = '';
fetch('/search.json')
.then(response => response.json())
.then(data_server => {
data = data_server;
});
search.addEventListener('input', event => {
search_term = event.target.value.toLowerCase();
showList();
});
const showList = () => {
results.innerHTML = '';
if (search_term.length <= 0) return;
const match = new RegExp(`${search_term}`, 'gi');
let result = data.filter(name => match.test(name.title));
if (result.length == 0) {
const li = document.createElement('li');
li.innerHTML = `No results found 😢`;
results.appendChild(li);
}
result.forEach(e => {
const li = document.createElement('li');
li.innerHTML = `<a href="${e.url}">${e.title}</a>`;
results.appendChild(li);
});
};
});
@yansusanto
Copy link

Thank you for sharing this, Chris. I'm just wondering what would be the best way to search for tags too? If I may ask.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment