JSFiddle - React, Tailwind, and code Playground

by Oski Krawczyk

HTML

<script src="https://goodies.pixabay.com/javascript/auto-complete/auto-complete.js"></script>
<form onsubmit="return false;" class="pure-form">
  <input id="hero-demo" autofocus type="text" name="q" placeholder="Search CDNJS...">
</form>

CSS

.autocomplete-suggestions {
    text-align: left; cursor: default; border: 1px solid #ccc; border-top: 0; background: #fff; box-shadow: -1px 1px 3px rgba(0,0,0,.1);

    /* core styles should not be changed */
    position: absolute; display: none; z-index: 9999; max-height: 254px; overflow: hidden; overflow-y: auto; box-sizing: border-box;
}
.autocomplete-suggestion { position: relative; padding: 0 .6em; line-height: 23px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 1.02em; color: #333; }
.autocomplete-suggestion b { font-weight: normal; color: #1f8dd6; }
.autocomplete-suggestion.selected { background: #f0f0f0; }

.version {
  color: #ccc;
}

.loading {
  background: yellow;
}

JavaScript

var input   = document.getElementById("hero-demo")
var headers = new Headers();
var options = {
	method:  'GET',
  headers: headers,
  mode:    'cors',
  cache:   'default'
};

new autoComplete({
  selector: 'input[name="q"]',
  source: function(term, response){
  	input.classList.add("loading")
  	var url = 'https://api.cdnjs.com/libraries?search=' + term + '&fields=version'
    
    fetch(url, options).then(function(response){
      return response.json()
    }).then(function(body){
    	input.classList.remove("loading")
      var arr = []
      results = body.results
  
      for (i = 0; i < results.length; i++){
      	arr.push([results[i].name, results[i].latest, results[i].version])
      }

      response(arr)
    })
  },
  renderItem: function (item, search){
    search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&amp;')
		var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi")
    
    return '<div class="autocomplete-suggestion" data-url="'+item[1]+'">'+item[0].replace(re, "<b>$1</b>")+' <span class="version">('+item[2]+')</span></div>'
  },
  onSelect: function(e, term, item){
    input.value = item.getAttribute("data-url")
  }
})