Skip to content

Commit

Permalink
Merge pull request #350 from koloml/autocomplete-mouse-selection
Browse files Browse the repository at this point in the history
Autocomplete: Prevent autocompleted options from selecting when cursor is placed right where popup is created
  • Loading branch information
liamwhite committed Aug 29, 2024
2 parents e0e375a + 53d345d commit 11d8ca0
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions assets/js/autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,18 +125,38 @@ function createItem(list: HTMLUListElement, suggestion: TermSuggestion) {
className: 'autocomplete__item',
});

let ignoreMouseOver = true;

item.textContent = suggestion.label;
item.dataset.value = suggestion.value;

item.addEventListener('mouseover', () => {
function onItemMouseOver() {
// Prevent selection when mouse entered the element without actually moving.
if (ignoreMouseOver) {
return;
}

removeSelected();
item.classList.add('autocomplete__item--selected');
});
}

item.addEventListener('mouseover', onItemMouseOver);

item.addEventListener('mouseout', () => {
removeSelected();
});

item.addEventListener(
'mousemove',
() => {
ignoreMouseOver = false;
onItemMouseOver();
},
{
once: true,
},
);

item.addEventListener('click', () => {
if (!inputField || !item.dataset.value) return;

Expand Down

0 comments on commit 11d8ca0

Please sign in to comment.