JSFiddle - React, Tailwind, and code Playground
by mlms13
HTML
<input type="text" name="name" id="test" autocomplete="off" />
<input type="text" name="email" />
CSS
body {
background: #eee;
font-family: sans-serif;
}
input {
width: 200px;
}
#suggestion {
background: #fff;
border: 1px solid #aaa;
border-top: 0;
box-shadow: 1px 1px 4px rgba(0,0,0,0.1);
display: none;
min-width: 202px;
padding: 0;
position: absolute;
}
#suggestion li {
cursor: default;
padding: 1px 6px;
}
#suggestion li.selected {
background: #4ad;
color: #fff;
}
JavaScript
function InputSuggestions() {
var self = this,
html = document.getElementsByTagName('html')[0],
suggestionBox = document.createElement('div'),
input = document.getElementById('test'),
selectedIndex = -1;
this.list = []; // this is the list of strings to filter on text input
this.inputID = ""; // the id of the text input
this.initialize = function () {
var parent = input.parentNode;
suggestionBox.setAttribute('id', 'suggestion');
parent.insertBefore(suggestionBox, input.nextSibling);
}
function buildSuggestionBox(suggestions) {
var list = document.createElement('ul'),
item,
i = 0;
if (suggestions.length < 1) {
return;
}
// empty the suggestion box to remove any existing suggestions
if (suggestionBox.hasChildNodes()) {
suggestionBox.removeChild(suggestionBox.getElementsByTagName('ul')[0]);
}
function makeHoverHandler(index) {
return function () {
var items = suggestionBox.getElementsByTagName('li');
// remove selection class from the existing selected item
// (including keyboard-selected)
if (selectedIndex > -1) {
items[selectedIndex].className = items[selectedIndex].className.replace(' selected', '');
}
items[index].className += ' selected';
selectedIndex = index;
};
}
function makeUnHoverHandler(item) {
return function () {
item.className = item.className.replace(' selected', '');
};
}
function makeClickHandler(item) {
return function () {
input.value = item.childNodes[0].nodeValue;
input.focus();
suggestionBox.style.display = "none";
};
}
for (i = 0; i <...