Welcome to the 49th Easy JavaScript tutorial, part of EasyProgramming.net. Let's do something a little fun and see how we can detect key presses. We've talked about event handlers and event listeners in the past where we can detect actions on DOM objects such as buttons. But wouldn't it be cool if you could detect that a person clicked on the caps lock? Or used a cool shortcut that you set up on your site.
The which and key properties of an event can tell you exactly what key triggered that event. Let's take a look:
which
and key
document.addEventListener("keydown",function(e){ console.log(e.which); //Returns the keycode (e.g. 16 for Shift) console.log(e.key); //Returns the key nane (e.g. Shift) });
To fork the fiddle and follow along: https://jsfiddle.net/easyjs/p01byocL/
Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!