Detect which key was pressed

Published on: May 28, 2017

Welcome to the 49th Easy JavaScript tutorial, part of 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:

Syntax of which and key

        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:

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!