Keyboard shortcuts in Drupal: Navigating through comments
It was one of the best features of Google Reader and Google GMail: the keyboard shortcuts, specially the ones to navigate through messages or posts (n = next, p = previous).
I decided it was time to implement it on spaniards.es, so here is the code I used. So far it only navigates through comments back and forth on the same page (does not go to next page or so). I am planning to add other shortcuts soon.
-
$(document).keyup(function(event) {
-
-
if (event.target.tagName == "INPUT" ||
-
event.target.tagName == "TEXTAREA")
-
return;
-
-
var selected = $('.comment-selected');
-
-
// Next comment
-
if (event.keyCode == 78) {
-
if (selected.length) {
-
selected.removeClass('comment-selected');
-
selected = selected.nextAll('.comment:first');
-
selected.addClass('comment-selected');
-
} else {
-
selected = $('.comment:first').addClass('comment-selected');
-
}
-
if (selected.length) {
-
window.scrollTo(0, selected.offset().top);
-
}
-
return;
-
}
-
-
// Previous comment
-
if (event.keyCode == 80) {
-
if (selected.length) {
-
selected.removeClass('comment-selected');
-
selected = selected.prevAll('.comment:first');
-
selected.addClass('comment-selected');
-
} else {
-
selected = $('.comment:last').addClass('comment-selected');
-
}
-
if (selected.length) {
-
window.scrollTo(0, selected.offset().top);
-
}
-
return;
-
}
-
});
As you can see, it is important to leave the input and textarea fields alone, so the keyboard shortcuts don’t interfere with the user typing some text. With a little bit of CSS the selected comment can be displayed with a different border color or background. And that’s it!
Check an example topic at www.spaniards.es