Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blocking default action on keypress with iframe

This is a catch 22 I can't really figure out how to resolve. Take this HTML5 game we host:

http://www.scirra.com/arcade/action/93/8-bits-runner - Warning has sound!

The page is hosted on scirra.com but the game is in an iframe on static1.scirra.net for security reasons.

Now if you press left and right, up or down when you are playing the game the entire window scrolls up and down, left and right. The prevent default seems to work OK when the game isn't focused. We want to prevent this default action when playing the game of course! So we use the code:

    var ar = new Array(32, 33, 34, 35, 36, 37, 38, 39, 40, 44);
    $(document).keydown(function (e) {            
        var key = e.which;
        if ($.inArray(key, ar) > -1) {
                e.preventDefault();
                return false;
        }
        return true;
    });

We put this on the parent page and the iframe page. When the iframe has focus left and right seem to be blocked, but not up and down.

Can anyone help us work out how to stop the page scrolling, AND still allow people to type comments in the comment box below the game? If you block space bar it stops people being able to add spaces in their text!

like image 360
Tom Gullen Avatar asked Feb 22 '23 05:02

Tom Gullen


1 Answers

I may not fully understand the problem, but it seems like you want:

  1. up, down, space, etc. to go only to the game window only when that has focus.
  2. up, down, space, etc. to go to the comment box when that has focus.
  3. up, down, space, etc. to go to the main window when that has focus.

Number #2 and #3 are what happen automatically if you do nothing. So basically you want #1. I don't see why you need any code on the main window.

This works in Chrome, Opera, FF, IE9, IE8, IE7 in my tests.

Main Window

Demo: http://jsfiddle.net/ThinkingStiff/Dp5vK/

HTML:

<iframe id="game" src="http://jsfiddle.net/ThinkingStiff/dtmxy/show/"></iframe>
<textarea id="comment-box"></textarea>

CSS:

#game {
    border: 1px solid red;
    display: block;
    height: 100px;
    width: 200px;
}

#comment-box {
    height: 100px;
    width: 200px;
}

body {
    height: 1000px;
    width: 1000px;
}

Game Window (iframe)

Demo: http://jsfiddle.net/ThinkingStiff/dtmxy/

Script:

$( document ).bind( 'keydown', function ( event ) {

    var keys = [32, 33, 34, 35, 36, 37, 38, 39, 40, 44];

    if( keys.indexOf( event.which ) > -1 ) {

        event.preventDefault();
        event.stopPropagation();

    };

} );
like image 184
ThinkingStiff Avatar answered Mar 06 '23 03:03

ThinkingStiff