Search Box

Search with suggestion

by Jitendra Pal

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="mainCt">
<h3>Search Box</h3>
  <div class="searchCt">
      <input name="searchBox" class="searchBox" id="searchBox" placeholder="Search here" maxlength="100" />
  </div>
  
  <p class='para'>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

CSS

body{
  width: 100vw;
  height: 100vh;
  font-family: sans-serif;
}
ul{
  list-style-type: none;
  padding-left: 0;
  margin: 0;
}
.hidden{
  display: none;
}
#main-ct{
  width: 100%;
  background-color: white;
}
.searchCt{
  width: 350px;
  position: relative;
}
.searchBox{
  width: 350px;
  height: 20px;
  font-size: 16px;
  border: none;
  padding: 5px 15px;
  margin: 0;
  left: 10px;
  outline: none;
  background-color: #ded;
}
.suggestions{
  width: 380px;
  background-color: white;
  font-size: 16px;
  position: absolute;
  opacity: 0.9;
}
.suggestion{
  cursor: pointer;
  padding:5px 15px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.suggestion:hover{
  background-color: #eee;
}
.para{
  font-family: cursive;
  width: 350px;
  padding: 15px;
}

JavaScript

// ================================= Mock Server Start =============================
var FAILURE_COEFF = 10;
var MAX_SERVER_LATENCY = 200;

function getRandomBool(n) {
  var maxRandomCoeff = 1000;
  if (n > maxRandomCoeff) n = maxRandomCoeff;
  return Math.floor(Math.random() * maxRandomCoeff) % n === 0;
}

function getSuggestions(text) {
  var pre = 'pre';
  var post = 'post';
  var results = [];
  if (getRandomBool(2)) {
    results.push(pre + text);
  }
  if (getRandomBool(2)) {
    results.push(text);
  }
  if (getRandomBool(2)) {
    results.push(text + post);
  }
  if (getRandomBool(2)) {
    results.push(pre + text + post);
  }
  return new Promise((resolve, reject) => {
    var randomTimeout = Math.random() * MAX_SERVER_LATENCY;
    setTimeout(() => {
      if (getRandomBool(FAILURE_COEFF)) {
        reject();
      } else {
        resolve(results);
      }
    }, randomTimeout);
  });
}
// ================================= Mock Server End =============================


// This "mySearch" is my whole module for this search box, only init method is exposed so anyone with this api can call init to ititialize this api

var mySearch = (function($){
  var config, fn;
  // config object is used for all the configuration that we have, easy to update here only
  config = {
    timeId: null,
    searchDelay: parseInt(MAX_SERVER_LATENCY) + 10,
    recentSearches: [],
    maxSuggestionShow: 10,
    maxSearchCharLength: 100
  }
  
  // this is private object having all the private methods to implement whole functionality
  fn={
  	_init: function(inputSelector){
      $(inputSelector).after("<div class='suggestions hidden'></div>");
      config.$searchBox = $(inputSelector);
      config.$suggestions = config.$searchBox.next(".suggestions");
    	fn._bindEvents(inputSelector);
      config.$searchBox.focus();
    },
    
    // bind all the required events on input
    _bindEvents: function(inputSelector){
      // Update suggestions when user types something in...