How would I add a listener for the Enter key?

document.querySelector('.check').addEventListener('click',  function () { };

I really would like the enter key to function exactly the same as a click on div.check –
I found the following online, however VS Code indicates that ‘key’ is depreciated.

event.key === "Enter"

I’m no expert on JS, but aren’t you missing event in the function definition?

ie function(event)

1 Like

We could do with a bit more context here, what happens when you click on div.check, and what is div.check?

Do you have a sample you can share with html included?

It’s just a number guessing game. I would just like the enter key to also check the player’s guess, same as clicking the check button. You can look over everything on this codepen

Hi @Cookachoo, had to look this up :slight_smile:

‘keydown’ and ‘keyCode’ should do the trick.

Just a test I did with your codepen

    'keydown', (event) => {
      // if not 'enter key' just exit here
      if (event.keyCode !== 13) return

Hope that helps.

document.querySelector('.check').addEventListener('click', function () {

// Runt the check function when 'Enter' is hit
document.querySelector('.guess').addEventListener('keydown', event => {
  if (event.keyCode !== 13) return console.log(;

So how would I combine these two listeners for dryer code?

They don’t really need combining. Here is a quick refactor.

const checkElem = document.querySelector('.check');
const guessElem = document.querySelector('.guess');

checkElem.addEventListener('click', function (event) {

guessElem.addEventListener('keydown', function (event) {
  if (event.keyCode === 13) checker(;

The checker function now only needs to deal with values.

const checker = function(value) {
  ... conditionals here

Just a note, I would recommend looking into classList to change the style on elements rather than using the style property.


.winner {
  background-color: #60b347;

.winner .number {
  width: 30rem;


if (value === secretNumber) {
  displayMessage('🎉 Correct Number 🎉')

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.