Opera preventDefault() on keydown event
Asked Answered
B

1

5

I'm trying to embed some keybindings in my webapp, and I'm having hard times with Opera. I have this code:

window.onkeydown = function(e){
  var key = e.keyCode ? e.keyCode : e.charCode ? e.charCode : false;
  if (e.ctrlKey && key === 84) {
    alert("foo");
    e.preventDefault();
    // return false;
  }
}

It works like a charm in Firefox and Chrome, but Opera still opens new tab. Same happens with return false;.

My info: Opera/9.80 (X11; Linux i686; U; en) Presto/2.7.62 Version/11.00

Becharm answered 23/1, 2011 at 12:47 Comment(0)
D
8

Opera doesn't support preventDefault on keydown, only on keypress.

As you can see in this example, you should bind a separate keypress handler for Opera (adapted to your situation):

var cancelKeypress = false;

document.onkeydown = function(evt) {
    evt = evt || window.event;
    cancelKeypress = (evt.ctrlKey && evt.keyCode == 84);
    if (cancelKeypress) {
        return false;
    }
};

/* For Opera */
document.onkeypress = function(evt) {
    if (cancelKeypress) {
        return false;
    }
};
Downspout answered 23/1, 2011 at 13:6 Comment(4)
@hallvors: You're welcome, but eh... what bug are you sorry about? Do you work for Opera?Downspout
Yes, I do :). This is one of the most common problems that trip up web developers and we should finally get aligned with other browsers before the next major release.Pumping
@hallvors: Ah, yes, I see now. Nice to have someone of Opera around here. BTW, that is indeed a horrible browser sniffing decision of Twitter, especially as they are using jQuery (and yes, I see the difference between input and textInput).Downspout
@hallvors: Just one more question: how are we going to detect it when Opera doesn't have this bug anymore? Detect the browser version with feature inference, like shown here? There's even a nice page that exactly describes which functions are supported. ;-)Downspout

© 2022 - 2024 — McMap. All rights reserved.