From c8bd0c9c33f3b667fb2b1108c27b13b5a86cef5b Mon Sep 17 00:00:00 2001 From: KoloMl Date: Thu, 29 Aug 2024 03:31:43 +0400 Subject: [PATCH 1/2] Require mouse movement before autocomplete options are selected on hover --- assets/js/autocomplete.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/assets/js/autocomplete.ts b/assets/js/autocomplete.ts index 21fd50dd..26797685 100644 --- a/assets/js/autocomplete.ts +++ b/assets/js/autocomplete.ts @@ -125,10 +125,17 @@ function createItem(list: HTMLUListElement, suggestion: TermSuggestion) { className: 'autocomplete__item', }); + let ignoreMouseOver = true; + item.textContent = suggestion.label; item.dataset.value = suggestion.value; item.addEventListener('mouseover', () => { + // Prevent selection when mouse entered the element without actually moving. + if (ignoreMouseOver) { + return; + } + removeSelected(); item.classList.add('autocomplete__item--selected'); }); @@ -137,6 +144,17 @@ function createItem(list: HTMLUListElement, suggestion: TermSuggestion) { removeSelected(); }); + item.addEventListener( + 'mousemove', + () => { + ignoreMouseOver = false; + item.dispatchEvent(new CustomEvent('mouseover')); + }, + { + once: true, + }, + ); + item.addEventListener('click', () => { if (!inputField || !item.dataset.value) return; From 53d345ddffd856febd2c1e5534662e777c1802af Mon Sep 17 00:00:00 2001 From: KoloMl Date: Thu, 29 Aug 2024 21:07:42 +0400 Subject: [PATCH 2/2] Moving `mouseover` handler into function for calling it from `mousemove` --- assets/js/autocomplete.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/assets/js/autocomplete.ts b/assets/js/autocomplete.ts index 26797685..2fecad0d 100644 --- a/assets/js/autocomplete.ts +++ b/assets/js/autocomplete.ts @@ -130,7 +130,7 @@ function createItem(list: HTMLUListElement, suggestion: TermSuggestion) { 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; @@ -138,7 +138,9 @@ function createItem(list: HTMLUListElement, suggestion: TermSuggestion) { removeSelected(); item.classList.add('autocomplete__item--selected'); - }); + } + + item.addEventListener('mouseover', onItemMouseOver); item.addEventListener('mouseout', () => { removeSelected(); @@ -148,7 +150,7 @@ function createItem(list: HTMLUListElement, suggestion: TermSuggestion) { 'mousemove', () => { ignoreMouseOver = false; - item.dispatchEvent(new CustomEvent('mouseover')); + onItemMouseOver(); }, { once: true,