Hide the suggestions list: suggestions.style.display = 'none'. Reset the currentHighlight to -1. The user can type again to see new suggestions.
Autocomplete Keyboard Navigation Implementation
How do you handle Escape key in an autocomplete search bar?
The answer
More FAQs in Autocomplete Keyboard Navigation Implementation
Track a currentHighlight index. ArrowDown increments (max: items.length - 1), ArrowUp decrements (min: 0), Enter selects the highlighted item, Escape closes. Toggle a 'highlighted' CSS class on the active item. Reset on new input.
If currentHighlight >= 0, prevent default and trigger the highlighted item's click: items[currentHighlight].click(). If no item is highlighted, let the form submit normally.
Use Math.min to clamp: currentHighlight = Math.min(currentHighlight + 1, items.length - 1). This prevents the highlight from going beyond the last item.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.