I have a Google Instant style search script written in jQuery. When a user searches, a URL is created which is something like #search/QUERY/1/ and their query is put in the title of the page. This currently happens as they type however I want it to do this only after they have stayed on the result page for 3 seconds. How can I do this?
My code is:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&category=web';
window.location.hash='search/'+query+'/1/';
document.title=$(this).val()+" - My Search Script";
if(search==''){
window.location.hash='';
document.title='My Search Script';
}
$.ajax({
type:"GET",
url开发者_如何学C:yt_url,
dataType:"html",
success:function(response){
if(response !=""){
$("#result").html(response);
} else {
$("#result").html("Your search did not return any results");
}
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});
You want to the change the title of the page once the user has been on the results page for 3 seconds. That means once the ajax success function has finished and the results have been rendered, 3 seconds from then, you want to change the title.
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&category=web';
window.location.hash='search/'+query+'/1/';
//document.title=$(this).val()+" - My Search Script";
if(search==''){
window.location.hash='';
document.title='My Search Script';
}
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
if(response !=""){
$("#result").html(response);
// schedule a function to change the page title after 3 seconds
setTimeout(function() {
document.title = search + " - My Search Script";
}, 3000);
}
else {
$("#result").html("Your search did not return any results");
// reset the title
document.title='My Search Script';
}
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});
Though if you ask me, no need to wait for 3 seconds. Change it the moment the search results are returned.
You can wrap your function inside the setTimeout function like:
setTimeout(function(){ }, 3000);
精彩评论