How to create a dynamic search box?
On this site - http://www.euescolhiesperar.com / - 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!
0
Author: winiercape, 2018-09-28
1 answers
You can listen to the event keyup from 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 do a debounce in the event to not perform many searches at the same time (example of debounce and throttle ).
In the following example, I am using the debounce function from the lodash library 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>
3
Author: fernandosavio, 2018-09-28 18:06:49