Skip to content

Instantly share code, notes, and snippets.

@ehq
Forked from bocha/gist:5754636
Last active December 18, 2015 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehq/5754640 to your computer and use it in GitHub Desktop.
Save ehq/5754640 to your computer and use it in GitHub Desktop.
$("#search").keydown(function(e) {
var $resultsUl = $("#suggested-result");
var $currentSelection = $resultsUl.find("li.highlighted:visible");
if ($currentSelection.length == 0) return;
if (e.keyCode == 40) { // keyCode 40 == down
var $next = $currentSelection.next();
if ($next.length > 0) {
$currentSelection.removeClass("highlighted");
$next.addClass("highlighted").focus();
if (! $next.is(":visible")) {
$resultsUl.scrollTop(
$next.offset().top - $resultsUl.offset().top + $next.height()
);
}
}
}
if (e.keyCode == 38) { // KeyCode 38 == up
var $prev = $currentSelection.prev();
if ($prev.length > 0) {
$prev.addClass("highlighted").focus();
$currentSelection.removeClass("highlighted");
if (! $prev.is(":visible")) {
$resultsUl.scrollTop(
$prev.offset().top - $resultsUl.offset().top + $prev.height()
);
}
}
}
if (e.keyCode == 13) { // KeyCode 13 == enter
window.location = $currentSelection.find("a").attr("href");
e.preventDefault();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment