Question

I have a website mainly consisting of vertical pages with photos. I want visitors to be able to use the arrow keys (up & down, left & right) on their keyboards to move upwards and downwards.

I tried a code shared here at overflow, but I can only make it work upwards with the up-arrow on my keyboard. When I press the other arrows nothing happens. I've tested in Chrome and Firefox in OS X on my MacBook Pro. View my test-page.

Are there any code modifications I can do to make it work?

This is the code I tried:

var handler = function(e) {
e = e || window.event;
var k = e.keyCode || e.which;
switch(k) {
  case 37:
    document.body.scrollLeft -= 1000;
    document.documentElement.scrollLeft -= 1000;
    break;
  case 38:
    document.body.scrollTop-= 1000;
    document.documentElement.scrollTop-= 1000;
    break;
  case 39:
    document.body.scrollLeft += 1000;
    document.documentElement.scrollLeft += 1000;
    break;
  case 40:
    document.body.scrollLeft += 1000;
    document.documentElement.scrollLeft += 1000;
    break;
  default: return true;
  }
  if( e.preventDefault) e.preventDefault();
  return false;
};
if( window.attachEvent) window.addEvent("onkeydown",handler,false);
else window.addEventListener("keydown",handler,false);
Was it helpful?

Solution

Scroll left and right wont work if the page is not wider than the screen. You have assigned scrollLeft to the key 40 (down) so nothing will happen. The following code is corrected and works for up and down:

var handler = function(e) {
e = e || window.event;
var k = e.keyCode || e.which;
switch(k) {
  case 37:
    console.log("37 pressed");
    document.body.scrollLeft -= 1000;
    document.documentElement.scrollLeft -= 1000;
    break;
  case 38:
    console.log("38 pressed");
    document.body.scrollTop-= 1000;
    document.documentElement.scrollTop-= 1000;
    break;
  case 39:
    console.log("39 pressed");

    document.body.scrollLeft += 1000;
    document.documentElement.scrollLeft += 1000;
    break;
  case 40:
    console.log("40 pressed");
    document.body.scrollTop += 1000;
    document.documentElement.scrollTop += 1000;
    break;
  default: return true;
}
if( e.preventDefault) e.preventDefault();
return false;
}; 
if( window.attachEvent) window.addEvent("onkeydown",handler,false);
else window.addEventListener("keydown",handler,false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top