A Typeahead is something like Googleโs search. When you type something into the search bar, you get a dropdown of items you can select from.
Weโre going to build a Typeahead that helps users type a country. Hereโs what weโre building together.
Typeahead vs Autocomplete
Typeahead can also be called Autocomplete because it helps users to complete what theyโre typing.
Browsers have a feature called autocomplete. The Typeahead weโre building is different from browsersโ autocomplete feature. Do not get confused!
Browsersโ autocomplete feature (sometimes called autofill) allows users filled things they filled in beforeโeven if theyโre things from other websites. Theyโre commonly used to fill stuff like name, address, and credit card information.
In contrast, Typeahead predicts what users want to type. It can contain any kind of information.
Anatomy of a Typeahead
A Typeahead contains two elements:
- An input field
- A list
The input field allows users to type things. Weโll add things to the list based on things they typed.
Building the Typeahead (HTML and CSS)
Typeahead are usually used in forms, so weโll place our typeahead inside a <form>. Make sure you set the formโs autocomplete to off to disable browsersโ autocomplete feature.
<form action="#" autocomplete="off"> <div class="typeahead"> <input name="country" id="country" /> </div></form>We want to populate a list based on things users type into the input field. Weโll put this list inside .typeahead, after the input.
<form action="#" autocomplete="off"> <div class="typeahead"> <input name="country" id="country" /> <ul> <li>Country 1</li> <li>Country 2</li> <li>Country 3</li> </ul> </div></form>You should see this in your browser:
We want to hide the <ul> when the page loads. We donโt know what the user will type yet, so we canโt make a prediction.
We can hide the <ul> with the hidden attribute.
<form action="#" autocomplete="off"> <div class="typeahead"> <input name="country" id="country" /> <ul hidden> <li>Country 1</li> <li>Country 2</li> <li>Country 3</li> </ul> </div></form>Thatโs it for the HTML and CSS! Letโs move to the next lesson and begin building the Typeahead.
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson