Stop page from scrolling when intercepting keystrokes such as spacebar and arrows

I use JavaScript and Prototype and catch keystrokes from the user. I successfully catch return, space and arrows with this code:

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 arrows continue to scroll through the page. Is there a way to keep them from scrolling?

+7
javascript prototypejs events scroll keyboard
source share
4 answers

From prototype documentation :

Event.stop (event)
Stopping the propagation of events and preventing its default action from triggering ultimately.

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

In addition, you must do this for the keydown event, because keyup too late.

+5
source share

Use e.preventDefault() to stop the default browser behavior

+7
source share

It is too late in keyup to prevent the default browser action. Do this in the keydown event and use the Prototype 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; } }); 
+6
source share

e.preventDefault () works in Chrome.

0
source share

All Articles