Autocomplete Search (debounce + keyboard + outside click)
Requirements
Render the autocomplete UI as the main component. Typing filters a fixed city list and shows results in a dropdown. Debounce input by ~300ms before searching. If query is empty (after trim): close dropdown and clear results. If query is non-empty: open dropdown and show results. Show up to 8 results. Keyboard support: ArrowUp/ArrowDown to move active option, Enter to select, Esc to close. Close dropdown on outside click. Highlight the matched substring using <mark> (escape HTML first). Show a 'Loading…' row while async search is pending (avoid flashing 'No results' during loading).
What the checks look for
The checks find elements by control labelled "Search", option, listbox, body, mark, text "No results", text "Loading…". Keep these in your markup.
Expected behavior
Focus with non-empty query opens the dropdown. Typing updates results after debounce + simulated latency. Arrow keys cycle through visible options (wrap around). Enter selects the active option, sets input value, closes dropdown. Esc closes dropdown and clears active selection. Clicking an option selects it (mousedown to avoid blur issues). Clicking outside closes dropdown and clears active selection. When loading: dropdown can be open but shows 'Loading…' instead of 'No results'. When not loading and results are empty: show 'No results'.
Implementation notes
Use Vue 3 Composition API in <script setup>. Use refs for query/isOpen/activeIndex/results/isLoading. Use a debounced watcher on query to trigger async search. Use stale-result protection (sequence id or cancellation flag) so older searches don’t override newer ones. Use document mousedown listener for outside click.
Solution idea
Use watch(query) with a 300ms timeout to debounce. On non-empty query, open dropdown and set loading true, then call an async search(q) that simulates latency and returns up to 8 matches. Protect against stale updates using a sequence counter. Add keyboard handling to move activeIndex and select results. Use document.addEventListener('mousedown', ...) to close on outside click.
Public interview reports
These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.
- Taro: Apple front end developer interview, August 2022
One self-reported 45-minute virtual interview asked for an autocomplete search bar in TypeScript with Vue or React, plus basic TypeScript and framework concept questions. This component practises the shape, not the reported wording.
- Code360: Booking.com frontend engineer interview experience, April 2023
One account describes a 40-minute round with three engineers: create an autocomplete text box in vanilla JavaScript, HTML and CSS, covering edge cases and must-haves versus nice-to-haves. This starter is a practice version in Vue; the reported round was framework-free.
- enginebogie: Booking.com frontend engineer machine-coding round, May 2023
One account describes a 60-minute machine-coding round: a typeahead with API calls, a live dropdown, highlighted matches, debounce or throttle, caching, keyboard navigation and error states. This starter is a practice version of that round in Vue, not its reported wording.
Reported in a public Apple interview account. Apple frontend interview questions
Reported in a public Booking.com interview account. Booking.com frontend interview questions
Solution
Overview
Use watch(query) with a 300ms timeout to debounce. On non-empty query, open dropdown and set loading true, then call an async search(q) that simulates latency and returns up to 8 matches. Protect against stale updates using a sequence counter. Add keyboard handling to move activeIndex and select results. Use document.addEventListener('mousedown', ...) to close on outside click.
Key ideas
- Debounce + async search
- Loading state to avoid 'No results' flicker
- Active index wrap-around navigation
- Escape HTML before inserting <mark>
- Outside click close
Single component (Composition API) with debounced watcher
Keep everything in App.vue. Store state in refs: query, isOpen, activeIndex, results, isLoading. Debounce query changes with a timeout. When searching, bump a seq counter and only apply results if the sequence matches. Implement onKeyDown to wrap selection and select on Enter. Use a document mousedown handler to detect clicks outside the root element.
Files
{
"name": "vue-autocomplete-search-solution",
"version": "0.1.0",
"private": true,
"dependencies": {
"vue": "3.x"
},
"scripts": {
"serve": "vue-cli-service serve"
}
}
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"allowJs": true
}
}
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vue SDK • Autocomplete (solution)</title></head><body><div id="app"></div></body></html>:root {
color-scheme: dark;
}
html,body {
margin: 0;
height: 100%;
background: #0a0a0a;
}
body {
font-family: system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;
}
.page {
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
background: #0a0a0a;
color: #e5e7eb;
}
.card {
width: 100%;
max-width: 520px;
background: #0b1020;
border: 1px solid #1f2937;
border-radius: 14px;
padding: 18px;
display: grid;
gap: 14px;
}
.title {
margin: 0;
font-size: 18px;
font-weight: 800;
}
.label {
display: block;
font-size: 12px;
color: #9ca3af;
margin-bottom: 6px;
}
.combo {
position: relative;
}
.input {
width: 100%;
padding: 12px 12px;
border-radius: 12px;
border: 1px solid #374151;
background: #0a0f1e;
color: #e5e7eb;
outline: none;
}
.input:focus {
border-color: #a3e635;
box-shadow: 0 0 0 2px rgba(163,230,53,.15);
}
.list {
position: absolute;
z-index: 10;
left: 0;
right: 0;
margin-top: 8px;
max-height: 240px;
overflow: auto;
border-radius: 12px;
border: 1px solid #1f2937;
background: #0a0f1e;
}
.option {
padding: 10px 12px;
cursor: pointer;
border-bottom: 1px solid rgba(31,41,55,.5);
}
.option:last-child {
border-bottom: none;
}
.option.active {
background: rgba(163,230,53,.12);
}
.empty {
padding: 10px 12px;
color: #9ca3af;
}
.hint {
margin: 0;
color: #9ca3af;
font-size: 12px;
}
mark {
background: rgba(163,230,53,.25);
color: #e5e7eb;
border-radius: 4px;
padding: 0 2px;
}
<template>
<main class="page">
<section class="card">
<h1 class="title">Autocomplete</h1>
<div
ref="rootRef"
class="combo"
role="combobox"
aria-haspopup="listbox"
:aria-expanded="isOpen"
:aria-owns="listboxId"
:aria-activedescendant="activeDesc"
>
<label class="label" for="q">Search</label>
<input
id="q"
class="input"
type="text"
autocomplete="off"
placeholder="Type a city..."
:value="query"
@input="onInput"
@focus="onFocus"
@keydown="onKeyDown"
/>
<ul v-if="isOpen" class="list" role="listbox" :id="listboxId">
<li
v-for="(item, i) in results"
:key="item"
class="option"
:class="{ active: i === activeIndex }"
role="option"
:id="optionId(i)"
:aria-selected="i === activeIndex"
@mousedown="select(item)"
v-html="highlight(item, query)"
/>
<li v-if="isLoading" class="empty">Loading…</li>
<li v-else-if="results.length === 0" class="empty">No results</li>
</ul>
</div>
<p class="hint">Keyboard: ↑/↓ navigate, Enter select, Esc close.</p>
</section>
</main>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
const listboxId = 'autocomplete-listbox';
const CITIES: string[] = [
'Amsterdam', 'Ankara', 'Athens', 'Austin',
'Barcelona', 'Berlin', 'Boston', 'Brussels',
'Chicago', 'Copenhagen',
'Dubai',
'Edinburgh',
'Frankfurt',
'Hamburg',
'Istanbul', 'Izmir',
'London', 'Los Angeles',
'Madrid', 'Miami', 'Milan', 'Munich',
'New York',
'Oslo',
'Paris', 'Prague',
'Rome',
'San Diego', 'San Francisco', 'San Jose', 'Seattle',
'Tokyo',
'Vienna',
'Zurich'
];
function sleep(ms: number) {
return new Promise<void>((res) => setTimeout(res, ms));
}
const rootRef = ref<HTMLElement | null>(null);
const query = ref('');
const isOpen = ref(false);
const activeIndex = ref(-1);
const results = ref<string[]>([]);
const isLoading = ref(false);
const activeDesc = computed(() => (activeIndex.value >= 0 ? optionId(activeIndex.value) : undefined));
let debounceHandle: number | undefined;
let seq = 0;
let pickedValue: string | null = null;
watch(query, (next) => {
const q = String(next ?? '').trim();
if (debounceHandle != null) {
window.clearTimeout(debounceHandle);
debounceHandle = undefined;
}
// A pick fills the input, but it is not a new search.
if (next === pickedValue) {
pickedValue = null;
seq++;
isLoading.value = false;
return;
}
if (!q) {
isOpen.value = false;
activeIndex.value = -1;
results.value = [];
isLoading.value = false;
return;
}
isOpen.value = true;
activeIndex.value = -1;
isLoading.value = true;
const mySeq = ++seq;
debounceHandle = window.setTimeout(async () => {
const data = await search(q);
if (seq !== mySeq) return;
results.value = data;
isLoading.value = false;
}, 300);
});
function onInput(e: Event) {
const el = e.target as HTMLInputElement | null;
pickedValue = null;
query.value = el?.value ?? '';
}
function onFocus() {
const q = query.value.trim();
if (q) isOpen.value = true;
}
function onKeyDown(ev: KeyboardEvent) {
if (ev.key === 'Escape') {
isOpen.value = false;
activeIndex.value = -1;
return;
}
if (!isOpen.value && (ev.key === 'ArrowDown' || ev.key === 'ArrowUp')) {
const q = query.value.trim();
isOpen.value = !!q;
}
const len = results.value.length;
if (!isOpen.value || len === 0) return;
if (ev.key === 'ArrowDown') {
ev.preventDefault();
activeIndex.value = activeIndex.value < 0 ? 0 : (activeIndex.value + 1) % len;
return;
}
if (ev.key === 'ArrowUp') {
ev.preventDefault();
activeIndex.value = activeIndex.value < 0 ? len - 1 : (activeIndex.value - 1 + len) % len;
return;
}
if (ev.key === 'Enter') {
if (activeIndex.value >= 0 && activeIndex.value < len) {
ev.preventDefault();
select(results.value[activeIndex.value]);
}
return;
}
}
function select(value: string) {
pickedValue = value;
query.value = value;
isOpen.value = false;
activeIndex.value = -1;
}
function optionId(i: number): string {
return `opt-${i}`;
}
function highlight(item: string, queryRaw: unknown): string {
const q = String(queryRaw ?? '').trim();
if (!q) return escapeHtml(item);
const idx = item.toLowerCase().indexOf(q.toLowerCase());
if (idx < 0) return escapeHtml(item);
const before = escapeHtml(item.slice(0, idx));
const mid = escapeHtml(item.slice(idx, idx + q.length));
const after = escapeHtml(item.slice(idx + q.length));
return `${before}<mark>${mid}</mark>${after}`;
}
function escapeHtml(s: string): string {
return s
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\"/g, '"')
.replace(/'/g, ''');
}
function onDocMouseDown(e: MouseEvent) {
const root = rootRef.value;
const target = e.target as Node | null;
if (!root || !target) return;
if (!root.contains(target)) {
isOpen.value = false;
activeIndex.value = -1;
}
}
onMounted(() => {
document.addEventListener('mousedown', onDocMouseDown);
});
onBeforeUnmount(() => {
document.removeEventListener('mousedown', onDocMouseDown);
if (debounceHandle != null) {
window.clearTimeout(debounceHandle);
debounceHandle = undefined;
}
});
async function search(q: string): Promise<string[]> {
const needle = q.toLowerCase();
const filtered = CITIES
.filter((c) => c.toLowerCase().includes(needle))
.slice(0, 8);
await sleep(150);
return filtered;
}
</script>
import 'zone.js';
import { createApp } from 'vue';
import App from './App.vue';
import './App.css';
createApp(App).mount('#app');
Notes & Pitfalls
Showing 'No results' while a request is still in flight (fix with isLoading).Not trimming query, causing dropdown to open for whitespace. Letting stale async responses overwrite newer results (fix with seq/cancel). Using clickinstead ofmousedownon options (blur can close dropdown before select).Injecting raw HTML into v-html without escaping (escape first). Reopening the dropdown after a pick: filling the input with the picked city is not a new search.
Debouncing with setTimeoutinsidewatchand clearing on cleanup.Stale-result protection with a sequence ref. Wrap-around navigation using modular arithmetic.
Common mistakes on this challenge
A pick or an outside click must close the dropdown for good
Filling the input with the picked city looks like a new query, so a debounced search can reopen the dropdown after it closed. Mark the picked value, then skip opening the dropdown when the search stream or watcher sees that same value. Clear the mark on the next real input event so typing still opens the dropdown. Listen for mousedown on the document and close only when the target is outside the component.
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.