Opera preventDefault () on keydown event

I am trying to embed some key bindings in my webapp and I have 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 a new tab. The same thing happens with return false;.

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

+5
source share
1 answer

Opera does not support preventDefault on keydown, only on keypress.

As you can see in this example , you must bind a separate handler keypressfor 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;
    }
};
+8
source

All Articles