0

The Problem

I made a "Type Ahead" search feature in Javascript that returns results that match what you are typing. The search results are returned as list items (with links) and are added to the DOM, but the links do not open up on the first click, and they did not show up when I tested a mouseenter eventlistener function that logs elements you enter on the page. I thought the problem might be with z-index, but I set both the li and a to a higher index and that didn't help.

const arr = ['pink', 'blue', 'green', 'purple'];

function findMatches(wordToMatch, arr) {
  return arr.filter(item => {
    const regex = new RegExp(wordToMatch, 'gi');
    return item.match(regex);
  });
}

function displayArr() {
  const matchArray = findMatches(this.value, arr)
  const html = matchArray.map(item => {
    const regex = new RegExp(this.value, 'gi');
    const itemName = item.replace(regex, `<span class='hl'>${this.value}</span>`);
    return `
      <li>
       <span class='name'>${itemName}</span>
      </li>
      `;
  }).join('');
  suggestions.innerHTML = html;
}

const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');

searchInput.addEventListener('keyup', displayArr);

//check for element
const all = document.querySelectorAll('a, ul, li, span, form, input');

function logElement(e) {
  console.log(e.target);
}

all.forEach(a => a.addEventListener('mouseenter', logElement));
<form class="search-form">
  <input type="text" class="search" placeholder="Search">
  <ul class="suggestions"></ul>
</form>

As you'll see, the lowest element you can get to is the ul I'm not sure if this is a CSS or JS problem.
Thank you in advance for your help.

Ravi Makwana
  • 1,864
  • 1
  • 20
  • 29
wkmfos
  • 3
  • 3

0 Answers0