r/webdev • u/PrudentKumquat • Oct 06 '26
Question Search box supporting autocomplete suggestions
I'm trying to write a toy web app (music server/jukebox) as a learning project. I need a search box which responds to input by showing a transient list of autocomplete suggestions. Right now it's an <input type="search"> with the suggestions in an <ol>. I populate it with <li> elements created on the fly. Functionally it's all working, so now I 'just' need to add the styling, and I'm finding everything looks shit.
It occurs to me that I've seen millions of these things, so perhaps there are de facto standard implementations which everyone uses in practice? Failing that, please could someone point me to a tutorial or other resource? (I tried the sub's faq and resource list but nothing jumped out at me).
6
u/Background-Front-925 Oct 06 '26
Datalist a html 5 component, try that
2
u/yihuaxiang Oct 07 '26
Your input + ol approach is basically what the libraries do under the hood, so I'd keep it. Position the list absolutely under the input, give it a max-height with overflow auto, a subtle shadow, and a background on the active item. Add role=listbox and aria-activedescendant for arrow keys and it'll feel like the ones you've seen everywhere.
3
u/fiskfisk Oct 06 '26
There's a million existing libraries made for different frameworks; I've standardized on TomSelect internally, as it's framework agnostic, so we can use it for any project we have.
2
u/nunoverissimopt Oct 06 '26
Your <input> plus generated <ol> is a reasonable starting point. You don’t need a library just to make the suggestions look like a dropdown. Put both inside a wrapper and position the list relative to it: .search {
position: relative;
width: min(100%, 28rem);
}
.search input {
box-sizing: border-box;
width: 100%;
padding: .75rem 1rem;
}
.search ol {
position: absolute;
z-index: 10;
top: calc(100% + .25rem);
left: 0;
right: 0;
margin: 0;
padding: .25rem;
list-style: none;
max-height: 16rem;
overflow-y: auto;
background: white;
border: 1px solid #ccc;
border-radius: .5rem;
box-shadow: 0 8px 24px #0002;
}
.search li {
padding: .75rem;
border-radius: .25rem;
}
.search li:hover,
.search li[aria-selected="true"] {
background: #eee;
}
Render or show the list only when there are suggestions. That should give you a clean baseline you can style to match your app.
One separate task: make sure it works with Arrow Up/Down, Enter and Escape, not just a mouse. The W3C’s Editable Combobox With List Autocomplete example is a useful reference for that behavior: https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-autocomplete-list/
4
u/[deleted] Oct 06 '26
[removed] — view removed comment