The first function I have provided would really terse things up. Basically, the only difference between the two methods is whether next or prev is called, so the function accepts this value as an argument and works for both directions.
As far as the base functionality, it basically attempts to select the next or prev tr
. If the element doesn't exist, it does nothing. If it does exist it just toggles the classes.
Javascript Method 0
function arrow(dir) {
var activeTableRow = $('.table tbody tr.active')[dir](".table tbody tr");
if (activeTableRow.length) {
$('.table tbody tr.active').removeClass("active");
activeTableRow.addClass('active');
}
};
$(window).keydown(function (key) {
if (key.keyCode == 38) {
arrow("prev");
}
if (key.keyCode == 40) {
arrow("next");
}
});
Working Example: http://jsfiddle.net/7TmJc/4/
Javascript Method 1
function arrowUp() {
var activeTableRow = $('.table tbody tr.active').prev(".table tbody tr");
if (activeTableRow.length) {
$('.table tbody tr.active').removeClass("active");
activeTableRow.addClass('active');
}
};
function arrowDown() {
var activeTableRow = $('.table tbody tr.active').next(".table tbody tr");
if (activeTableRow.length) {
$('.table tbody tr.active').removeClass("active");
activeTableRow.addClass('active');
}
};
$(window).keydown(function (key) {
if (key.keyCode == 38) {
arrowUp();
}
if (key.keyCode == 40) {
arrowDown();
}
});
Working Example: http://jsfiddle.net/7TmJc/3/