3

I have an input field with a JS focusout event. Under my input field, I have an autocomplete popup with suggestions. But when I click on a suggestion, it’s playing the focusout before the event listener on the click of the autocomplete! Any clues on how I can I fix this conflict?

Picture of the input and its autocompletion:

Picture of the input and its autocompletion

The click event:

resultsFrom.addEventListener('click', (event) => {
  let e;
    e = event.target.parentNode;
  inputFrom.value = e.getAttribute('data-display');
});

The focusout event:

inputFrom.addEventListener('focusout', () => {
  const list = document.querySelector('#results-from');
  let first = list.firstChild;
  inputFrom.value = first.getAttribute('data-display');
  resultsFrom.innerHTML = '';
});
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Bonapara
  • 359
  • 3
  • 16

1 Answers1

3

The focusout event has a property on the event object of relatedTarget - this is the element that's going to gain the focus, in this case, it will be the element you're clicking on.

You need to check if that element is within your results, and not clear them out if that's the case. Something like this:

inputFrom.addEventListener('focusout', (e) => {
  const list = document.querySelector('#results-from');
  if (!list.contains(e.relatedTarget)) {
    //the target is not in the list, continue as before
    //otherwise allow the click to function by not clearing out resultsFrom
    let first = list.firstChild;
    inputFrom.value = first.getAttribute('data-display');
    resultsFrom.innerHTML = '';
  }
});
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • Ok - check out [this related answer](https://stackoverflow.com/a/42764495/791010) then - in addition to my answer above, you need to make it so the elements you're clicking on can gain focus. Either by using an element that can receive focus by default, or that answer suggests that adding `tabindex="0"` to your `
  • `s should also work.
  • – James Thorpe May 14 '18 at 10:40
  • Thanks so much you're right. It works like a charm with tabindex="0". – Bonapara May 14 '18 at 11:17