1

I have the following keydown event function:

@HostListener('keydown', ['$event'])   
myFunc(e: KeyboardEvent) {
            if (e.which === 13 || e.which === 32) {
                e.preventDefault();
                foo();
            }
        }

If I remove the e.preventDefault(), the function is working correctly only in Chrome. And only Enter key is not working on the IE11 and Firefox. But when I add preventDefault(), it works on all the browsers correctly.

My question is, what exact behavior preventDefault() is blocking here in Firefox and IE11? Could anyone help me out with an explanation.

Thank you.

Tumen_t
  • 795
  • 5
  • 14
ShellZero
  • 4,415
  • 12
  • 38
  • 56
  • `what exact behavior preventDefault() is blocking` - it is preventing default behaviour – Jaromanda X Feb 16 '17 at 19:53
  • @JaromandaX What is the default behavior of the Enter key in these two browsers which it is preventing? – ShellZero Feb 16 '17 at 19:56
  • yes, that's right – Jaromanda X Feb 16 '17 at 19:57
  • I'd have to read some documentation - let me google that for you – Jaromanda X Feb 16 '17 at 19:58
  • `Enter key is not working on the IE11 and Firefox` - how is the browser stopping the enter key from working? Or do you mean your function doesn't work as expected? what happens instead of the intended behaviour? That could be a clue as to what default behaviour preventDefault is preventing - because the default behaviour is not a fixed behaviour - e.g. depends on what type of element is in focus – Jaromanda X Feb 16 '17 at 20:00
  • https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which See the big red banner? – Teemu Feb 16 '17 at 20:08
  • @JaromandaX helps! when I hit enter, the function needs to be called and then a click event has to get emitted from the foo(). I did place console messages inside them and it does pass the enter if condition, both the console messages are even showed but the click event didn't get emitted. – ShellZero Feb 16 '17 at 20:09
  • @Teemu Yes, I did see that, but the alternate is to use .key which isn't supported by IE11 yet! – ShellZero Feb 16 '17 at 20:10
  • `key` is supported in IE11 for sure, it is supported even in IE9. – Teemu Feb 16 '17 at 20:12
  • I am sorry, key is supported but for the spacebar it is not returning " ". Yeah, I can definitely use a work around for that though. – ShellZero Feb 16 '17 at 20:16
  • Check: 1)http://stackoverflow.com/questions/4479216/does-internet-explorer-supports-e-preventdefault 2) http://stackoverflow.com/questions/1000597/event-preventdefault-function-not-working-in-ie – Marian07 Feb 16 '17 at 21:16

0 Answers0