Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
elements scroll by jk shortcut
function registerJumpElements(elements) {
var KEYCODE_J = 74;
var KEYCODE_K = 75;
var targetElements = elements;
var currentIndex = -1;
var scollElement = function(event) {
if (event.keyCode != KEYCODE_J && event.keyCode != KEYCODE_K) {
return;
}
// 次の位置を計算
var nextIndex =
currentIndex + ((event.keyCode == KEYCODE_J) ? 1 : -1);
if (nextIndex < 0) {
nextIndex = 0;
} else if (nextIndex >= targetElements.length) {
nextIndex = targetElements.length - 1;
}
// 要素が表示されるようにスクロール
targetElements[nextIndex].scrollIntoView();
currentIndex = nextIndex;
}
if (document.addEventListener) {
document.addEventListener(
'keydown', scollElement, false);
} else {
// IE8など
document.attachEvent(
'onkeydown', scollElement);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.