How to create a dynamic search box?

0

On this site - link - when you type in the search box, the results appear instantly without having to press enter. How can I do this on Blogger?

Thank you!

    
asked by anonymous 28.09.2018 / 19:36

1 answer

2

You can listen to the keyup event of the input and run the search after that.

Example:

var search = document.getElementById('search');
var log = document.getElementById('log');

/*
  - keyup é lançado a cada tecla pressionada no input
*/
search.addEventListener('keyup', function() {
  // Cria um <li> e adiciona na <ul> apenas para exemplificar
  var li = document.createElement('li');
  li.innerHTML = "Pesquisando: " + this.value;
  log.insertBefore(li, log.firstChild);
});
<input id="search">
<hr>
<ul id="log"></ul>

For performance reasons, you can debounce in the event not to perform many searches at the same time ( debounce and throttle example ).

In the following example, I'm using the library debounce function lodash for convenience reasons:

var search = document.getElementById('search');
var log = document.getElementById('log');

/*
  - keyup é lançado a cada tecla pressionada no input
  - debounce faz com que a função só executa depois que
o usuário parar de digitar por 1 segundo
*/
search.addEventListener('keyup', _.debounce(function() {
  // Cria um <li> e adiciona na <ul> apenas para exemplificar
  var li = document.createElement('li');
  li.innerHTML = "Pesquisando: " + this.value;
  log.insertBefore(li, log.firstChild);
}, 1000));
<script src="https://unpkg.com/[email protected]/lodash.min.js"></script><inputid="search">
<hr>
<ul id="log"></ul>
    
28.09.2018 / 20:06