listen to 'CTRL+N' with javascript

2.8k views Asked by At

I am trying to bind the 'CTRL+N' key combination, like this:

var ctrlPressed = false;
    var nCode = 78;
    var ctrlCode = 224;
    var cmdCode = 17;
    document.addEventListener ("keydown", function(e){
        if( e.keyCode == ctrlCode || e.keyCode == cmdCode){
            ctrlPressed = true;
        }else{
            ctrlPressed = false;
        }
        console.log(e.keyCode);
    });
    document.addEventListener ("keyup", function(e){
        if(ctrlPressed && e.keyCode == nCode){
             e.preventDefault();
            nou_element(parent);
            return;
        }
    });

Please note: jQuery isn't avaliable

The thing is that the e.preventDefault() doesn't seem to override the create window functionality built into the bowser

how can I bypass?

1

There are 1 answers

2
Oriol On BEST ANSWER

You code has some problems:

  • Not all browsers allow you to prevent default keyboard actions (like Chromium 30)

  • To prevent them on the others (like Firefox or IE8), you must prevent keydown event instead of keyup one, because then it's too late.

  • To check if Ctrl key is pressed, use e.ctrlKey

Demo (for Firefox)

document.addEventListener("keydown", function(e){
    if(e.ctrlKey && e.keyCode == /*key code*/) {
        e.preventDefault();
        /* Do whatever */
    }
});

Demo (for Firefox & IE8)

document.onkeydown =  function(e){
    e = e || window.event;
    if(e.ctrlKey && e.keyCode == nCode) {
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
        /* Do whatever */
        return false;
    }
};