diff --git a/resources/ts/form/input-handler.ts b/resources/ts/form/input-handler.ts index 577df2d..1eaf7bb 100644 --- a/resources/ts/form/input-handler.ts +++ b/resources/ts/form/input-handler.ts @@ -6,6 +6,7 @@ import { toggleSingleActiveFilter } from '../filters/active-filters'; const INPUT_SELECTOR = '.c-degree-programs-sarchform__input'; const MIN_CHARACTERS = 3; + export const SEARCH_ACTIVE_FILTER_LABEL = _x( 'Keyword', 'frontoffice: degree-programs-overview', @@ -19,12 +20,12 @@ const initLiveSearching = () => { let timeout: ReturnType< typeof setTimeout > | null = null; - input?.addEventListener( 'input', () => { + const handleInput = () => { if ( timeout ) { clearTimeout( timeout ); } - const inputValue = input.value.trim(); + const inputValue = input?.value.trim() || ''; if ( inputValue.length > MIN_CHARACTERS ) { timeout = setTimeout( () => { @@ -32,22 +33,34 @@ const initLiveSearching = () => { timeout = null; }, INPUT_DELAY ); } - } ); + }; + + input?.addEventListener( 'input', handleInput ); }; -if ( ! isReducedMotion() ) { - initLiveSearching(); -} +let valueOnFocusEvent = ''; -input?.addEventListener( 'blur', () => { - const inputValue = input.value.trim(); +const handleFocus = () => { + valueOnFocusEvent = input?.value.trim() || ''; +}; - if ( inputValue.length > MIN_CHARACTERS ) { - return; +const handleBlur = () => { + const inputValue = input?.value.trim() || ''; + + if ( + inputValue.length <= MIN_CHARACTERS && + valueOnFocusEvent !== inputValue + ) { + submitForm(); } +}; - submitForm(); -} ); +if ( ! isReducedMotion() ) { + initLiveSearching(); +} + +input?.addEventListener( 'focus', handleFocus ); +input?.addEventListener( 'blur', handleBlur ); input?.addEventListener( 'search', () => { submitForm(); } ); @@ -58,7 +71,6 @@ export const toggleSearchActiveFilter = () => { } const inputValue = input.value.trim(); - toggleSingleActiveFilter( SEARCH_ACTIVE_FILTER_LABEL, inputValue ); };