I’m using this scrollTo script from webdesignerwall, and trying to add keyboard control.
The original script:
$(function () {
function scroll(direction) {
var scroll, i, positions = [],
here = $(window).scrollTop(),
collection = $('.post');
collection.each(function () {
positions.push(parseInt($(this).offset()['top'], 10));
});
for (i = 0; i < positions.length; i++) {
if (direction == 'next' && positions[i] > here) {
scroll = collection.get(i);
break;
}
if (direction == 'prev' && i > 0 && positions[i] >= here) {
scroll = collection.get(i - 1);
break;
}
}
if (scroll) {
$.scrollTo(scroll, {
duration: 750
});
}
return false;
}
$("#next,#prev").click(function () {
return scroll($(this).attr('id'));
});
});
And for the keyboard control I try to add something like this:
$(window).keypress(function(event) {
switch (event.keyCode) {
case 38: // key is up
return scroll($(this).attr('id'));
case 40: // key is down
return scroll($(this).attr('id'));
}
});
Thanks for your help.
It should be:
See it in action at jsFiddle. (Click anywhere in the Result pane to activate keyboard control.)
Note: Don’t override common UI keys, like the arrows, for things like this! It will play havoc with keyboard users (or all users if text boxes are ever used). Also, in this case, it will cause “jumpy” behavior anyway.
I’ve remapped the functionality to AltN and AltP.
(In the demo jsFiddle, I’ve left in the arrow keys, so you can see some of the problems with that mapping.)