Created
February 17, 2014 03:28
-
-
Save jsatk/9044223 to your computer and use it in GitHub Desktop.
Adds basic arrow navigation to your site. Easy to change and customize. Ideal for blog or article-based websites. jQuery is required, although I may make a jQuery-less version soon.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ArrowJumpTo = function (event, elements) { | |
var keyCheck, | |
scrollToElement, | |
getElementPositions, | |
getPositionToScrollTo; | |
keyCheck = function (event, elements) { | |
if ([38, 40].indexOf(event.keyCode) === -1) return false; | |
var els = elements || event.data.element; | |
els = $(els); // Ensure jQuery wrap. | |
scrollToElement(getElementPositions(els), event.keyCode); | |
}; | |
getElementPositions = function ($element) { | |
return $element.map(function (index, h1) { | |
return $(h1).offset().top; | |
}); | |
}; | |
scrollToElement = function (positions, keyPressed) { | |
$('html, body').animate({ | |
scrollTop: getPositionToScrollTo(positions, keyPressed) | |
}, 500); | |
}; | |
getPositionToScrollTo = function (positions, keyPressed) { | |
positions = $.makeArray(positions); | |
switch (keyPressed) { | |
case 38: | |
return positions.reverse().filter(function (value) { | |
return value < $(window).scrollTop(); | |
})[0]; | |
case 40: | |
return positions.filter(function (value) { | |
return value > $(window).scrollTop(); | |
})[0]; | |
} | |
}; | |
keyCheck(event, elements); | |
}; | |
$(document).ready(function () { | |
$(document).on('keyup', function (event) { | |
// Replace 'h1' with whatever element you'd like to | |
// jump to on arrow up or down. | |
ArrowJumpTo(event, 'h1'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment