ThomasDow
ThomasDow

Reputation: 19

Getting character and code from keyPressed

function convert(){
    String.fromCharCode();
    var out = document.getElementById("");
}


document.getElementById("=").addEventListener("keypress", convert);

The result should be the

I'm new to javascript and have this assignment, which has to be done exactly the way it's asked. I tried myself for a couple of hours, but I still need some help !

Thanks in advance :)

Upvotes: 1

Views: 55

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206102

  • Use insertAdjacentHTML (instead of el.innerHTML += html)
  • Attach your event listener to window or document

Using insertAdjacentHTML()

const EL_output = document.getElementById("output"); // Cache selector

function convert(ev) {
  const html = `You pressed ${ev.key} character code ${ev.keyCode}<br>`;
  EL_output.insertAdjacentHTML('beforeend', html);
}

document.addEventListener('keypress', convert);
<div id="output"></div>

Using Element.innerHTML and +=

const EL_output = document.getElementById("output"); // Cache selector

function convert(ev) {
  const html = `You pressed ${ev.key} character code ${ev.keyCode}<br>`;
  EL_output.innerHTML += html;
}

document.addEventListener('keypress', convert);
<div id="output"></div>

PS:

to attach the event listener to the actual #output element add the tabindex="0" attribute: <div id="output" tabindex="0"></div>

Upvotes: 1

OPTIMUS PRIME
OPTIMUS PRIME

Reputation: 1325

A little trick with CSS and \n new line char, to insert text, instead of HTML:

let out = document.getElementById("output");

document.addEventListener("keypress", function(e) {
  let char = String.fromCharCode(e.charCode);
  let message = `Pressed: ${char}, char code: ${e.charCode}\n`;
  
  out.insertAdjacentText('beforeend', message);
  out.scrollTop = out.scrollHeight;
});
#output {
  white-space: pre-line;
  max-height: 150px;
  overflow: auto;
}
Press any key...
<p id="output"></p>

Any changes with innerHTML or innerText / textContent - in fact rewrite all contents... insertAdjacent method only inserts a little piece.

Upvotes: 0

Related Questions