0

I am not sure how to do 'keydown' with pure JavaScript.

Here's how I did it with jQuery, but is there a way to do the same thing with pure JS also ? I just wanna check if there is a way and to learn how to do it, as well as to see difference and length of code. Thank you.

$('body').on('keydown', function(e) {
    if (e.keyCode === 27) return false;
});

EDIT: It is used to disable "Esc" button!

dvlden
  • 2,402
  • 8
  • 38
  • 61
  • 3
    Did you not search "keydown JavaScript" in your favorite search engine? – epascarello Mar 12 '13 at 13:10
  • http://stackoverflow.com/questions/3036243/cancel-the-keydown-in-html – Andrea Ligios Mar 12 '13 at 13:11
  • I did search indeed @epascarello. However none works. If I add alert or console log it works but if I wanna override something that has "close" on Esc press it wont work. Works with jQuery tho :/ – dvlden Mar 12 '13 at 13:17
  • Have fun with the cross browser issues in pure javascript - you know you CAN look at the jQuery source code to see how it is done there also...just sayin as that is exactly what you appear to be asking. – Mark Schultheiss Mar 12 '13 at 13:19
  • Why don't you show what does not work. – epascarello Mar 12 '13 at 13:19

4 Answers4

3

I don't like setting the listeners as attributes, so I add even listeners like this:

var ele = document.getElementById('test');
ele.addEventListener('keydown', function() {
    //code
}, false);
Jeff Shaver
  • 3,315
  • 18
  • 19
1

Here you go

document.body.onkeydown = function(e) {
    if (e.keyCode === 27) return false;
}

As you can see jQuery is shorter but this will execute less code

Dreamwalker
  • 3,032
  • 4
  • 30
  • 60
0

Try this,

HTML

<body onkeydown="YourFunction(event)">...</body>

JS

function YourFunction(e)
{
     var unicode=e.keyCode || e.charCode|| e.which;
     if(unicode == 27)
        return false;
     else
     {
        //Your code...
     } 
}
Manikandan Sethuraju
  • 2,873
  • 10
  • 29
  • 48
0

In pure javascript it is done this way

document.body.onkeydown=function(e){
  key=e.keyCode || e.charCode|| e.which; //cross browser complications
  if(key===27){
    return false;
  }
}

Hope it helped, it is the same script as the JQuery one you provided

Ronnie
  • 512
  • 5
  • 12