1

I am trying to get the key pressed inside a div. But I am not sure how to just get the key pressed. Currently as I try to press the key nothing happens.

The way I am doing is.

<div contenteditable="true" id="d"> </div>

<p id="log"></p>


const input = document.querySelector('input');
const log = document.getElementById('log');

document.getElementById("d").addEventListener("onkeyup", logKey)

function logKey(e) {
   log.textContent += ` ${e.code}`;
}

Here is also the jsfiddle corresponding to it: https://jsfiddle.net/hpeLqmyg/

How could I do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Amanda
  • 2,013
  • 3
  • 24
  • 57

3 Answers3

2

change onkeyup to keyup

document.getElementById("d").addEventListener("keyup", logKey)

https://jsfiddle.net/2x8pcu0m/

Lev Buchel
  • 532
  • 5
  • 14
0

Try this, you have a mistake in your code.

replace onkeyup with just keyup

const input = document.querySelector('input');
const log = document.getElementById('log');

document.getElementById("d").addEventListener("keyup", logKey)

function logKey(e) {
   log.textContent += e.code;
}
#d {
  width:50%;
  color:red;
  background-color: yellow;
}
<div contenteditable="true" id="d"> </div>

<p id="log"></p>
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59
0

Change onkeyup tokeyup

const log = document.getElementById('log');

document.getElementById("d").addEventListener("keyup", logKey)

function logKey(e) {
  log.textContent += ` ${e.code}`;
}
<div contenteditable="true" id="d"> </div>

<p id="log"></p>

You can also use e.key instead of code

const log = document.getElementById('log');

document.getElementById("d").addEventListener("keyup", logKey)

function logKey(e) {
  log.textContent += ` ${e.key}`;
}
div {
  border: 1px solid red;
}
<div contenteditable="true" id="d"> </div>

<p id="log"></p>
brk
  • 48,835
  • 10
  • 56
  • 78