Off the top of my head, make a list of the top
offsets of each image, and then when pressing the down/up arrows, compare the scrollTop
position to the image positions to determine which one is closest in the up/down direction.
var locs = [];
// Save offsets of each image
// Use a better selector in real life
$('img').each(function () {
locs.push($(this).offset().top);
});
$(document).keydown(function (e) {
switch (e.which) {
case 37:
case 38:
case 83:
// Get the current scroll position
var sTop = parseInt($(document).scrollTop());
// For UP, go through the list backward until
// you find one before the current scroll position
for (i = locs.length-1; i >= 0; i--) {
if (locs[i] < sTop) {
$(document).scrollTop(locs[i]);
break;
}
}
break;
case 39:
case 40:
case 68:
// Get the current scroll position
var sTop = parseInt($(document).scrollTop());
// For DOWN, go through the list until
// you find one after the current scroll position
for (i = 0; i < locs.length; i++) {
if (locs[i] > sTop + 1) {
$(document).scrollTop(locs[i]);
break;
}
}
break;
default:
return true;
}
return false;
});