How to create a dynamic search box?

Asked

Viewed 220 times

0

On this website - http://www.euescolhiesperar.com/ - when you type in the search box, the results appear instantly without being required to press enter. How can I do this in Blogger?

Thank you!

1 answer

3

You can hear the event keyup input and run the search after this.

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 make a debauch in the event not to perform many searches at the same time (example of debauchery and Throttle).

In the following example, I am using the function debauch library lodash for reasons of practicality:

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>

<input id="search">
<hr>
<ul id="log"></ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.