The first click isn't firing and I can't work out why.
All subsequent clicks work fine. If I reload the page, same problem: first click: nothing happens.
I've tried accessing other html elements as test in the queryselector
but it doesn't make a difference.
Here's the code (I'm trying to do this in vanilla JS):
const cities = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data =>cities.push(...data));
function findMatches(wordToMatch, cities) {
return cities.filter(place => {
const regex = new RegExp(wordToMatch, 'gi');
return place.city.match(regex) || place.state.match(regex)
});
}
function displayMatches() {
const matchArray = findMatches(this.value, cities);
const html = matchArray.map(place => {
const regex = new RegExp(this.value, 'gi');
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
return `
<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${numberWithCommas(place.population)} </span>
</li>
`;
}).join('');
suggestions.innerHTML = html;
// this only works on the second click:
const searchResult = document.querySelectorAll('li');
searchResult.forEach(el => {
el.addEventListener('click', function(){
console.log('hi');
})})
const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
searchInput.addEventListener('change', displayMatches); // change only fires once user navigates away from input field!
searchInput.addEventListener('keyup', displayMatches);
}