Reputation:
I'm trying to make a search bar which is loading dynamicly content.
However I wish the real content loading start after the user end typing.
I tried this version but it does not work because it does not take into count each event "keyup".
let old_search = ""
let search = ""
$("#search_input").on('keyup paste',function(){
$("#loader_active").show()
$('#videos').empty()
let old_search = $("#recherche").val()
setTimeout(function (){
search = $("#search_input").val()
console.log(old_search + ">" + search)
if (search == old_search){
console.log("loading")
start = 0;
limit = 20;
load(search, start, limit);
start += limit;
}
}, 1000);
});
function load(search, start=0, limit=20) {
$("#loader_active").show()
let form_data = new FormData();
form_data.append('search', search);
form_data.append('start', start);
form_data.append('limit', limit);
$.ajax({
url: "http://website.com/ajax/videos.php",
contentType: false,
dataType: "json",
processData: false,
cache: false,
data: form_data,
type: 'POST',
success: function (data) {
$(data).each(function(index, value) {
showVideo(value) // show video creates divs with jquery containing the data from the json received by the ajax call
})
$("#loader_active").hide()
}
})
}
Does any body know any solution ?
Upvotes: 0
Views: 466
Reputation: 169
What you can do is to make your function reset a trigger that will fire after x amount of time. Something like:
function myCoolFunction(myParameters) {
//Clear the timeout every time this happens
clearTimeout(window.myTimeout);
//Create a new timeout
window.myTimeout = setTimeout(function() {
//Do Something after 1 second
}, 1000);
}
$(".selector").on('keyup paste', function (){
myCoolFunction(myParameters);
});
This will execute 1 second after the last 'keyup/paste'. :D
Upvotes: 1