Created
June 15, 2021 06:22
-
-
Save rebelchris/f252a845dc4a4a4d66ca707ad3f5b0c5 to your computer and use it in GitHub Desktop.
Static website search
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
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); | |
}); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.