I've made a search engine for my database table where the search query gets sent by Jquery AJAX to a file called search.php. Search.php then sends the result back to the Javascript file where the results are processed and added to index.php.
Everything works perfectly except when I try to add arrow key navigation. For example, I want the first item in the search results page to be selected ( by appending the class, "red" to it and using "focus()" ) when I press the down arrow key, the second result to be selected when I press it again, etc..
Nothing gets selected when I press either the up or down arrow key. I'm testing this in Google Chrome.
index.php:
PHP Code:
<style>
#search_results{
border:1px solid blue;
width:300px;
position:absolute;
background:white;
display:none;
}
#search_results ul li{
}
#search{
width:300px;
height:30px;
}
.red{
background:red;
}
</style>
Start searching: <input type="text" id="search" autocomplete="off">
Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
<div id="search_results">
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="search.js"></script>
search.js:
Code:
$(document).ready(function(){
search_x = $('#search').offset().left;
search_y = $('#search').offset().top;
search_height = $('#search').height();
$('#search_results').css({
'left': search_x,
'top': (search_y + search_height + 5)
});
//arrow key navigation
start = -1;
$(document).keydown(function(e) {
if(e.keyCode == 38){
if (start == -1){
start = ($('#search_results ul li a').size() - 1);
}else{
start--;
if (start < 0){
start = ($('#search_results ul li a').size() - 1);
}
}
$('#search_results ul li a').removeClass('red').focus();
$('#search_results ul li a').eq(start).addClass('red').focus();
}
if(e.keyCode == 40){
if (start == -1){
start = 0;
}else{
start++;
if (start > ($('#search_results ul li a').size() - 1)){
start = 0;
}
}
$('#search_results ul li a').removeClass('red').focus();
$('#search_results ul li a').eq(start).addClass('red').focus();
}
});
$('#search').keyup(
function(){
var search_term = $(this).val();
$.post(
'search.php',
{
search_term : search_term
},function(data){
if (data == "nothing"){
$('#search_results').fadeOut();
} else {
$('#search_results').html(data).fadeIn();
}
});
});
});
$('body').click(function(){
$('#search_results').fadeOut();
});