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?
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?
Share Improve this question edited Dec 29, 2011 at 12:24 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Oct 2, 2010 at 9:08 Pablo FernandezPablo Fernandez 287k139 gold badges401 silver badges642 bronze badges 4- What's the best way to notify you using the "@" notation? @J.Pablo or @JPablo? Any idea of which works? – brainjam Commented Oct 2, 2010 at 11:04
- @brainjam Just copy and paste the user name. I think actually, SO only pays attention to the first part of the name up to the space, so @J. would work. Or, commenting on the question as you did does the trick. – JAL Commented Oct 2, 2010 at 11:11
- @Alex, I think at least 3 characters are necessary. See meta.stackexchange.com/questions/43019/… – brainjam Commented Oct 2, 2010 at 12:05
- I didn't even know SO would do something special with @; amazing! – Pablo Fernandez Commented Oct 2, 2010 at 13:08
4 Answers
Reset to default 8Use e.preventDefault()
to Stop default behavior of browser
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;
}
});
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.
e.preventDefault() works in Chrome.