1
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 :)

ThomasDow
  • 19
  • 3
  • Inside your event handler, you can use `event.keyCode` to get the Unicode value of the pressed key. [More info](https://www.w3schools.com/jsref/event_key_keycode.asp) – phwt Nov 25 '19 at 02:29
  • What does "Slide 39" says? – Roko C. Buljan Nov 25 '19 at 02:30
  • Possible duplicate of [JavaScript KeyCode vs CharCode](https://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode) – Chris Nov 25 '19 at 02:55

2 Answers2

1
  • 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>

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

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.

OPTIMUS PRIME
  • 1,297
  • 9
  • 20