Created
February 6, 2018 20:53
-
-
Save mayashavin/7734c7a42d3578de7a77860ed530b598 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
If you were building a search tool and wanted search results to pop up as you | |
typed but the server call was taxing, write a function that gets called on every | |
key down but calls the server when the user stops typing for 400ms. | |
*/ | |
// <input type="text" class="js-search"> | |
/* | |
Questions to ask: | |
1. Each of input should have unique id, where is the id in this case? | |
2. Where to display search results? | |
3. How many search input there will be in one page? | |
4. URL Query request format? | |
5. What about error in request response? | |
6. What is the format of result? String? JSON? | |
*/ | |
(function(){ | |
var searchTool = { | |
timer: 400, | |
query: (str) => { | |
let params = new URLSearchParams(`q=${str}`).toString(); | |
fetch(`http://localhost:3000/?${params}`) | |
.then((result) => { | |
document.getElementById('search-result').innerHTML = result; | |
}) | |
.catch((err) => console.log(err)) | |
}, | |
bindToSearchBoxes: function(ids){ | |
var inputs = document.querySelectorAll(`input#${ids}`); | |
var onKeyDown = (() =>{ | |
var lastRequest; | |
return (e) => { | |
if (lastRequest){ | |
clearTimeout(lastRequest); | |
} | |
lastRequest = setTimeout(()=>{ | |
searchTool.query(e.target.value); | |
}, searchTool.timer); | |
} | |
})(); | |
for(var i = 0; i < inputs.length; i++){ | |
inputs[i].addEventListener('keydown', onKeyDown); | |
} | |
} | |
}; | |
searchTool.bindToSearchBoxes('search1'); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input type="text" class="js-search" id="search1"> | |
<div id="result"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment