简体   繁体   中英

JavaScript code that makes an alert box showing the keycode of the key you pressed is not working

I'm trying to make a Javascript code that makes an alert box pop up when you press a key, telling you the keycode of that key. Unfortunately, it does not seem to be working.

function showKeycode(e) {  
  alert(e.keyCode);  
}
document.onKeydown = showKeycode;

Whenever I press a key, no alert box pops up.

When using in JavaScript the event name should be onkeydown not onKeydown :

 function showKeycode(e) { alert(e.keyCode); } document.onkeydown = showKeycode; 

Though I prefer using addEventListener() to attach the event:

 function showKeycode(e) { alert(e.keyCode); } document.addEventListener('keydown',showKeycode); 

Javascript is case sensitive, the proper name would be "onkeydown". Also, you should be assigning window.onkeydown instead of document.onkeydown, and ideally, it is best to use addEventListener instead of directly assigning a listener in the manner you chose, ie element.onsomeevent = some_handler; .

Use onkeydown instead of onKeydown .

 document.onkeydown = evt => alert(evt.keyCode); 

Don't forget to click on the white area when running the snippet to shift the focus to the right document.

Also, you should use document.addEventListener('keydown', ...) instead of document.onkeydown = ... as it allows you to add multiple listeners that won't be overriden by others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM