Reputation:
I'm learning javascript through MDN documentation. They have an example on the function topic which apparently I'm unable to understand.
const textBox = document.querySelector("#textBox");
const output = document.querySelector("#output");
textBox.addEventListener('keydown', (event) => output.textContent = `You pressed "${event.key}".`);
I've read a few documentation onkey down function and I assume it is supposed to return some value for every character entered (correct me if I'm wrong); but in the example on MDN, it only returns enter when I press enter key and backspace when I press backspace (while input box has no other characters). I'm reading this example on a mobile device btw.
Upvotes: 1
Views: 116
Reputation: 304
You're almost right about the keydown
event. It's supposed to call the callBack function with each keydown press when the input HTML element is activated or it is able receive the event (the HTML element with the #textBox
id). It means that if the #textBox
element is not selected/activated, it will not listen to any 'keydown' event, and as a result it will not call the callBack function: (event) => output.textContent = You pressed "${event.key}".
keydown
is an event which is listened by the #textBox
element via addEventListener()
method. To be more clear, the addEventListener()
method sets up a function that will be called whenever the specified event is delivered to the target. The target in this case is the html element with the #textBox
id.
In short the code you wrote will add the keydown
event to the input element, and call the (event) => output.textContent = You pressed "${event.key}".
function when the event is happening.
You can read more about addEventListener() on MDN.
Upvotes: 1
Reputation: 19485
Seems to be working, as long as you add the proper html.
const textBox = document.querySelector("#textBox");
const output = document.querySelector("#output");
textBox.addEventListener('keydown', (event) => output.textContent = `You pressed "${event.key}".`);
<input id="textBox">
<div id="output"></div>
Upvotes: 0