Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop page from scrolling when intercepting key presses like space and arrows

I'm using JavaScript and Prototype and catching the key presses from the user. I successfully catch return, space and arrows with code like this:

Event.observe(window, "keyup", function(e) {
  switch (e.keyCode) {
    case Event.KEY_RETURN:
    case Event.KEY_RIGHT:
    case 32:  // space
      // do something
      break;
  }
});

My problem is that spaces and arrow keep on scrolling the page. Is there a way to keep them from scrolling the page?

like image 634
pupeno Avatar asked Oct 02 '10 09:10

pupeno


3 Answers

Use e.preventDefault() to Stop default behavior of browser

like image 135
Rahul Talar Avatar answered Nov 10 '22 00:11

Rahul Talar


It's too late in keyup to prevent the default browser action. Do it in the keydown event instead and use Prototype's Event.stop method:

Event.observe(document, "keydown", function(e) {
  switch (e.keyCode) {
    case Event.KEY_RETURN:
    case Event.KEY_RIGHT:
    case 32:  // space
      // do something
      Event.stop(e);
      break;
  }
});
like image 24
Tim Down Avatar answered Nov 10 '22 00:11

Tim Down


From the Prototype documentation:

Event.stop(event)
Stops the event’s propagation and prevents its default action from being triggered eventually.

So adding Event.stop(e); before the break; should solve your problem.

Also, you should be doing this for the keydown event, because keyup is too late.

like image 41
brainjam Avatar answered Nov 09 '22 23:11

brainjam