Free Web Design Code & Scripts

JavaScript Autocomplete Dropdown

Code Snippet:Vanilla Javascript Autocomplete
Author: bev
Published: 2 months ago
Last Updated: November 23, 2025
Downloads: 165
License: MIT
Edit Code online: View on CodePen
Read More

This tutorial will guide you through creating a powerful and user-friendly Javascript Autocomplete Dropdown feature. Autocomplete dropdowns enhance user experience by providing intelligent suggestions as they type, making forms and search functionalities more efficient and intuitive. The following steps provide a practical example that you can adapt and expand for various applications.

Step 1: Include Header Assets

First, add the necessary CSS normalize file link in the `head` section of your HTML file to ensure consistent styling across different browsers.

<link rel="stylesheet" href="https://public.codepenassets.com/css/normalize-5.0.0.min.css">

Step 2: Set Up the HTML Structure

Now, create the basic HTML structure for the search container, input field, and suggestions list. This provides the foundation for our autocomplete dropdown.

<div class="search-container">
	<input type="text" name="fruit" id="fruit" placeholder="Search fruit 🍎">
	<div class="suggestions">
		<ul></ul>
	</div>
</div>
    <script  src="./script.js"></script>

Step 3: Apply CSS Styling

Next, style the HTML elements using CSS to create a visually appealing and functional autocomplete dropdown. Customize the styles as needed to fit your design.

* {
  box-sizing: border-box;
}

:focus {
  outline: #e65c00 auto 5px;
}

body {
  font-family: sans-serif;
  display: flex;
  min-height: 100vh;
  align-items: center;
  justify-content: center;
  background: #e65c00;
  background: linear-gradient(to right, #f9d423, #e65c00);
}

input {
  border: 0 none;
}

.search-container {
  width: 400px;
  position: relative;
}
.search-container input,
.search-container .suggestions {
  width: 100%;
}
.search-container input {
  background: rgba(255, 255, 255, 0.2);
  height: 60px;
  padding: 0 10px;
}
.search-container .suggestions {
  position: absolute;
  top: 60px;
}

ul {
  display: none;
  list-style-type: none;
  padding: 0;
  margin: 0;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.2);
  max-height: 200px;
  overflow-y: auto;
}
ul.has-suggestions {
  display: block;
}
ul li {
  padding: 10px;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.2);
}
ul li:hover {
  background-color: #e65c00;
}

input {
  border-bottom: 2px solid #e65c00;
}

 

const input = document.querySelector('#fruit');
const suggestions = document.querySelector('.suggestions ul');

const fruit = [ 'Apple', 'Apricot', 'Avocado 🥑', 'Banana', 'Bilberry', 'Blackberry', 'Blackcurrant', 'Blueberry', 'Boysenberry', 'Currant', 'Cherry', 'Coconut', 'Cranberry', 'Cucumber', 'Custard apple', 'Damson', 'Date', 'Dragonfruit', 'Durian', 'Elderberry', 'Feijoa', 'Fig', 'Gooseberry', 'Grape', 'Raisin', 'Grapefruit', 'Guava', 'Honeyberry', 'Huckleberry', 'Jabuticaba', 'Jackfruit', 'Jambul', 'Juniper berry', 'Kiwifruit', 'Kumquat', 'Lemon', 'Lime', 'Loquat', 'Longan', 'Lychee', 'Mango', 'Mangosteen', 'Marionberry', 'Melon', 'Cantaloupe', 'Honeydew', 'Watermelon', 'Miracle fruit', 'Mulberry', 'Nectarine', 'Nance', 'Olive', 'Orange', 'Clementine', 'Mandarine', 'Tangerine', 'Papaya', 'Passionfruit', 'Peach', 'Pear', 'Persimmon', 'Plantain', 'Plum', 'Pineapple', 'Pomegranate', 'Pomelo', 'Quince', 'Raspberry', 'Salmonberry', 'Rambutan', 'Redcurrant', 'Salak', 'Satsuma', 'Soursop', 'Star fruit', 'Strawberry', 'Tamarillo', 'Tamarind', 'Yuzu'];

function search(str) {
	let results = [];
	const val = str.toLowerCase();

	for (i = 0; i < fruit.length; i++) {
		if (fruit[i].toLowerCase().indexOf(val) > -1) {
			results.push(fruit[i]);
		}
	}

	return results;
}

function searchHandler(e) {
	const inputVal = e.currentTarget.value;
	let results = [];
	if (inputVal.length > 0) {
		results = search(inputVal);
	}
	showSuggestions(results, inputVal);
}

function showSuggestions(results, inputVal) {
    
    suggestions.innerHTML = '';

	if (results.length > 0) {
		for (i = 0; i < results.length; i++) {
			let item = results[i];
			// Highlights only the first match
			// TODO: highlight all matches
			const match = item.match(new RegExp(inputVal, 'i'));
			item = item.replace(match[0], `<strong>${match[0]}</strong>`);
			suggestions.innerHTML += `<li>${item}</li>`;
		}
		suggestions.classList.add('has-suggestions');
	} else {
		results = [];
		suggestions.innerHTML = '';
		suggestions.classList.remove('has-suggestions');
	}
}

function useSuggestion(e) {
	input.value = e.target.innerText;
	input.focus();
	suggestions.innerHTML = '';
	suggestions.classList.remove('has-suggestions');
}

input.addEventListener('keyup', searchHandler);
suggestions.addEventListener('click', useSuggestion);

 

Loading... ...

Loading preview...

Device: Desktop
Dimensions: 1200x800
Lines: 0 Characters: 0 Ln 1, Ch 1

Leave a Comment

About W3Frontend

W3Frontend provides free, open-source web design code and scripts to help developers and designers build faster. Every snippet is reviewed before publishing for quality. Learn more.