Search code examples
javascripthtmlscrollkeydownpreventdefault

Prevent SPACE and ARROW from scrolling [Game Iframe]


I have a problem with preventing Space and Arrows to scroll down/up when the game is focused on an online gaming site for kids.

To prevent this functionality on a web page, I know, we can use:

window.addEventListener("keydown", function(e) {
        if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
            e.preventDefault();
        }
    }, false);

But, the problem is when the game is focused.

The games are mirrored through iframe and once the user will click on the game and the game iframe will focus, the code from above will just not work anymore.

Of course, it's frustrating because we have games where you need to use the Space or Up/Down Arrows to move, jump, or something else - but whenever you will press those buttons, the page will start scrolling.

Page example:

...
<body>
<iframe src="https://example.com/game/game21/index.html" width="X" height="Y"></iframe>
...

I don't have the right to modify the src page.


Solution

  • You're missing e.stopPropagation();. Try this:

    window.addEventListener("keydown", function(e) {
        if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
            e.preventDefault();
            e.stopPropagation();
        }
    });