JSFiddle - React, Tailwind, and code Playground

by Salmin Skenderovic

HTML

<div id="container">
  
<input type="text" id="input">
<div id="autocomplete"></div>

</div>

CSS

html {
  background-color: #fff;
  height: 100%;
}

input {
  padding: 5px 10px;
  font-size: 32px;
//  line-height: 32px;
  
}

#autocomplete {
  background-color: #00acd6;
  height: auto;
  width: 413px;
}

#autocomplete .item {
  padding: 0px 12px 5px 12px;
  font-size: 24px;
  color: #fff;
  width: 94.5%;
}

.h4 {
  font-weight: bold;
  color: #f7b228;
}

#autocomplete .item:hover, .item.active {
  cursor: pointer;
  background-color: #032352;
}

JavaScript

const cities = [
{name: "Helsingborg"},
{name: "Lund"},
{name: "Malmö"},
{name: "Ängelholm"},
{name: "Eslöv"},
{name: "Trelleborg"},
{name: "Ystad"},
{name: "Hässleholm"},
{name: "Kristianstad"}
]

const input = document.querySelector("#input");
const autocomplete = document.querySelector("#autocomplete");

let currentActive = -1;

input.addEventListener("keyup", displayMatches);
document.addEventListener("keyup", handleArrows);

function handleArrows(e) {
	if (e.key === "Enter" && currentActive !== -1) {
	  const city = autocomplete.querySelectorAll("#autocomplete .item")[currentActive];
  	selectCity(city);
    return;
  }
	if (!(e.keyCode === 40 || e.keyCode===38)) return;
  
  const items = autocomplete.querySelectorAll(".item");
  if (items.length === 0) return;

	const adjuster = (e.keyCode === 40) ? 1 : -1;
	const newActive = (currentActive + adjuster);

	// Check if we are at the begining or the end
  if (newActive < 0 || newActive ==  items.length) return true;

	// only remove if there is an active class
  if (currentActive !== -1) items[currentActive].classList.remove("active");

	// Add and set
	items[newActive].classList.add("active");
  currentActive = newActive;
  
  return;
}

function displayMatches(e) {
		
    // return if arrow keys or enter
		if ((e.keyCode === 40 || e.keyCode===38 || e.keyCode === 13)) return;

		//Reset
    currentActive = -1;
    
		// More than 2 letters
    if (this.value.length >= 2) {
    		const userInput = this.value;
    		// Filter results
        const matchArray = findMatches(this.value, cities);
        // If we get any results
        if (matchArray.length > 0) {
            const html = matchArray.map(function(city) {
              const index = city.name.toLowerCase().indexOf(userInput.toLowerCase());

							if (index !== -1) {
                const before = city.name.substr(0, index);
                const middle = city.name.substr(index, userInput.length);
                const after =...