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!
I may not fully understand the problem, but it seems like you want:
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.
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;
}
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();
};
} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With