Created
September 29, 2012 12:41
-
-
Save xenji/3803887 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
var Search = { | |
searchUrl: "http://search.xenji.com/xenjicom/_search", | |
processResults: function(results) { | |
if (typeof results != "undefined") | |
this.renderResults(results.hits); | |
}, | |
onkeypress: function(event) { | |
var $e = $('#search_string'); | |
var value = $e.val(); | |
if (value.length > 2) { | |
Search.search(value); | |
$('#searchresultcontainer').slideDown(); | |
} | |
if (value.length == 0) { | |
$('#searchresultcontainer').slideUp(); | |
} | |
}, | |
search: function(query) { | |
$.ajax(this.searchUrl, | |
{ | |
'data': {'q': query}, | |
'async': true, | |
'dataType': 'jsonp', | |
'crossDomain': true, | |
'jsonpCallback': 'Search.processResults' | |
}); | |
}, | |
renderResults: function(allResults) { | |
var r, $list = $('#searchresultlist'), template = '<dd class="srt_title"><a href="$a">$b</a></dd><dt class="srt_descr">$c</dt>'; | |
var resultsHtml = []; | |
if (allResults.total > 0) { | |
for (i in allResults.hits) { | |
r = allResults.hits[i]._source; | |
resultsHtml.push(template.replace('$a', r.url).replace('$b', r.title).replace('$c',r.content.substring(0,200) + '...')); | |
} | |
$list.html(resultsHtml.join("")); | |
} | |
else { | |
$list.html("No results."); | |
} | |
} | |
}; | |
$(document).ready(function(){ | |
var $s = $('#search_string'); | |
console.log('Register event handler'); | |
$s.on('keyup', Search.onkeypress); | |
$(document).on('keyup', function(e){ | |
var code = (e.keyCode ? e.keyCode : e.which); | |
if(code == 27 && $('#search_string').val() != '' && $('#searchresultcontainer').is(':visible')) { | |
$('#search_string').val(''); | |
$('#searchresultcontainer').slideUp(); | |
$('#searchresultlist').html(""); | |
$('#search_string').focus(); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment