Reputation: 19
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
Reputation: 206102
insertAdjacentHTML
(instead of el.innerHTML += html
) window
or document
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>
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
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