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

document
  .querySelector('.guess')
  .addEventListener(
    'keydown', (event) => {
      // if not 'enter key' just exit here
      if (event.keyCode !== 13) return
      
      console.log(event.target.value)
    })

Hope that helps.

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

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

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) {
  checker(Number(guessElem.value));
});

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

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.

css

.winner {
  background-color: #60b347;
}

.winner .number {
  width: 30rem;
}

javascript

if (value === secretNumber) {
  document.body.classList.add('winner')
  displayMessage('🎉 Correct Number 🎉')
}

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