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

aL3xa
  • 35,415
  • 18
  • 79
  • 112

1 Answers1

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;
    }
};
Community
  • 1
  • 1
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
  • 2
    Thanks for helping him and sorry about the bug :-( – hallvors Jan 25 '11 at 02:57
  • @hallvors: You're welcome, but eh... what bug are you sorry about? Do you work for Opera? – Marcel Korpel Jan 25 '11 at 11:57
  • 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. – hallvors Jan 26 '11 at 01:09
  • @hallvors: Ah, yes, I see now. Nice to have someone of Opera around here. BTW, [that](http://my.opera.com/hallvors/blog/why-twitter-doesnt-count) 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`). – Marcel Korpel Jan 26 '11 at 10:33
  • @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](http://www.howtocreate.co.uk/tutorials/jsexamples/sniffer.html)? There's even a [nice page](http://www.opera.com/docs/userjs/specs/) that exactly describes which functions are supported. ;-) – Marcel Korpel Jan 26 '11 at 16:21
  • you saved my life – Muthukumar Anbalagan Jul 04 '17 at 20:59