Jump to content

Keyboard preventDefault


brentstrandy
 Share

Recommended Posts

Even though my individual keys all have "preventDefault = true" and my keyboard event says "defaultPrevented = true" I'm still finding the DOM is processing my keyboard events.

I have the following event callback on keypress:

this.input.keyboard.on('keydown', e => {
  this.handleInput(e);
  e.preventDefault();
});

Am I using the "preventDefault" property correctly?

Link to comment
Share on other sites

I found the solution digging through the Phaser 3 code

event.preventDefault() will not be called unless the specific Key has been added to Phaser's Keyboard list of Keys. See Phaser 3 code below: 

var key = _this.keys[event.keyCode];

if (key && key.preventDefault)
{
    event.preventDefault();
}

Reference: https://github.com/photonstorm/phaser/blob/16f61b402b8aa50b09a869c85a840eed363e1052/src/input/keyboard/KeyboardPlugin.js#L234

When I add "this.input.keyboard.createCursorKeys();" to my code, the Keyboard object creates Keys for the directional (cursor) keys and will call preventDefault() on keydown events.

this.input.keyboard.createCursorKeys();
this.input.keyboard.on('keydown', e => {
  this.handleInput(e);
});

 

Link to comment
Share on other sites

  • 2 months later...

I'm also meeting this problem, except I'm writing a kind of terminal emulator and basically need to prevent default behavior on all key presses. It would be nice if the real event was exposed, or a utility function was available to cancel event bubbling in these cases.

Edit: The solution, it seems, is to simply add the keyCode of what you wish to prevent bubbling:

// backspace is keycode 8
create() {
    this.input.keyboard.addKey(8);
    // call a function for all keydown events. A backspace will not be
    // bubbled up through the DOM
    this.input.keyboard.on('keydown', some_keyboard_handler_function);
};

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...