Reputation: 99
The code below reads the unicode value of the key that was pressed down by the user and then prints it out on the screen. It works like intended:
document.addEventListener("keydown", getKey);
document.addEventListener("keyup", displayKey);
function getKey() {
var key = event.which || event.keyCode;
return key;
}
function displayKey() {
document.body.innerHTML = "Unicode value: " + getKey();
}
However, when I try to do the same thing with a class it doesn't work:
<div class="anyName">Press any key</div>
<script>
var n = document.getElementsByClassName("anyName");
n[0].addEventListener("keydown", getKey);
n[0].addEventListener("keyup", displayKey);
function getKey() {
var key = event.which || event.keyCode;
return key;
}
function displayKey() {
n[0].innerHTML = "Unicode value: " + getKey();
}
</script>
Why does it not work and how can I fix it? Any help is greatly appreciated!
Upvotes: 0
Views: 39
Reputation: 944530
This has nothing to do with arrays. getElementsByClassName
returns a NodeList, not an array. It has nothing to do with NodeLists either.
The problem here is that you are trying to bind the event handler to a div.
Unless you engage in shenanigans (with accessibility implications), you cannot give focus to a div. The div doesn't have any descendants that can receive focus either. Consequently, when the event from the key event bubbles, it never touches the div, so it doesn't fire the event handler.
Put something you can give the focus to inside the div, click on it, then press a key, and it will work.
var n = document.getElementsByClassName("anyName");
n[0].addEventListener("keydown", getKey);
n[0].addEventListener("keyup", displayKey);
function getKey() {
var key = event.which || event.keyCode;
return key;
}
function displayKey() {
n[0].innerHTML = "Unicode value: " + getKey();
}
<div class="anyName"><textarea></textarea></div>
Warning: You are using the global event object which is non-standard and not supported by Firefox. Use the first argument passed to the event handler to get the event object instead.
Upvotes: 2