W3C home > Mailing lists > Public > whatwg@whatwg.org > June 2010

[whatwg] Is there a way to stop scrolling when pressing directional arrows?

From: Simon Pieters <simonp@opera.com>
Date: Tue, 15 Jun 2010 00:56:26 +0200
Message-ID: <op.vebbccryidj3kv@simon-pieterss-macbook.local>
On Tue, 15 Jun 2010 00:16:13 +0200, Kornel Lesinski <kornel at geekhood.net>  
wrote:

> On Mon, 14 Jun 2010 20:38:07 +0100, Carlos Andr?s Sol?s  
> <csolisr at gmail.com> wrote:
>
>> Hello! I've been noticing a problem in many HTML5 test apps, very  
>> especially games. When the directional arrow buttons are pressed, the  
>> screen scrolls.
>> This is a problem that, as far as I know, Flash had solved by changing  
>> the focus of the application to the app. Is this doable in HTML5?
>
> Yes. It's possible already ? page just has to return false from keypress  
> handler:
>
> window.onkeypress = function(){return false}
>
> That's just one line that, unfortunately, many web-based games forget to  
> include.

If a game is embedded in a page with other content, it could make the  
<canvas> (or whatever) focusable with tabindex='0' and only disable keys  
when the game has focus. It could also be nice and only disable the keys  
it chooses to use.

<script>
var mapping = {37: 'left', 38: 'up', 39: 'right', 40:'down'}
function press(e) {
   if (!e.shiftKey && !e.ctrlKey && !e.metaKey && e.keyCode > 36 &&  
e.keyCode < 41) {
     var ctx = e.target.getContext('2d');
     ctx.clearRect(0, 0, e.target.width, e.target.height);
     ctx.fillText(mapping[e.keyCode], 20, 20);
     e.preventDefault();
   }
}
</script>
<canvas tabindex=0 onkeypress=press(event)></canvas>

In Opera, I can scroll using the arrow keys, navigate to the game,  
interact with it using the arrow keys without it scrolling the page, and  
navigate away from it using spatnav (shift+arrow keys).

-- 
Simon Pieters
Opera Software
Received on Monday, 14 June 2010 15:56:26 UTC

This archive was generated by hypermail 2.4.0 : Wednesday, 22 January 2020 16:59:24 UTC