In my HTML, I have created a simulated keyboard with buttons that correspond to characters. When you click on these buttons, the character is added to a text element on the screen. Additionally, you can use your physical keyboard to input characters in the same way.
However, I've encountered an issue where pressing the spacebar or enter key on the physical keyboard after clicking an onscreen button causes the character from the button to be repeated. This problem only occurs with the space and enter keys, and only when using the physical keyboard in combination with clicking an on-screen button.
To better illustrate the bug, here is a code snippet. Click on the interactive area to focus it and then start typing. Everything should work fine until you click the 'a' button followed by pressing the spacebar - at which point 'a' starts repeating unnecessarily.
window.addEventListener('keypress',function(e) {
// console.log(e.key);
keyClick(e.key);
}
);
function keyPress(key) {
if (key == "Space") {
document.getElementById('text').textContent = document.getElementById('text').textContent + " ";
}
}
function keyClick(key) {
// console.log("poop");
if (key == "Space") {
document.getElementById('text').textContent = document.getElementById('text').textContent + " ";
} else {
document.getElementById('text').textContent = document.getElementById('text').textContent + key;
}
}
<body>
<div id="text"></div>
<button id="a" onClick="keyClick(this.id)">a</button>
</body>
Initially, I thought the issue might be due to different functions handling the physical and simulated keyboards. However, even after combining them, the problem persists. By adding a parameter to the function, I noticed that the extra character is being triggered by the onclick event of the HTML button when I press the spacebar key. It seems like there's something obvious I'm overlooking, or perhaps this is just a strange bug.