I am working on an app that uses both onkeyup and onclick events. onkeyup is working as expected, however, onclick is not working as expected. See the code below...
//the state
const [currentGuess, setCurrentGuess] = useState("");
//the callback function
const handleKeyup = (e) => {
let pressedKey = "";
if (typeof e == "string") {
pressedKey = e;
}
const checkPressedKey = pressedKey ? pressedKey : e.key;
setCurrentGuess((prev) => prev + checkPressedKey);
console.log(currentGuess.length);
}
//triggering callback when user types on keyboard
useEffect(() => {
window.addEventListener("keyup", handleKeyup);
return () => window.removeEventListener("keyup", handleKeyup);
}, [handleKeyup]);
//trigger the callback when user types in the fake keyboard
useEffect(() => {
setKeyOnClick();
}, []);
function setKeyOnClick() {
const allkey = document.querySelectorAll(".key");
allkey.forEach((btnKey) => {
btnKey.addEventListener("click", function () {
handleKeyup(btnKey.dataset.key);
});
});
}
***for onKeyup**
output: 0, 1, 2, 3, 4 ....
***for onclick**
output: 0 (it doesn't increase);
-HTML-
<button className="key" data-key="Q">Q</button>
<button className="key" data-key="W">W</button>
<button className="key" data-key="E">E</button>
<button className="key" data-key="R">R</button>
<button className="key" data-key="T">T</button>
<button className="key" data-key="Y">Y</button>
As you can see above i have to pass the dataset-key in the handlekeyup function for onclick event.
Your buttons have className="key", so if you want to get elements by class name you have to use a dot in querySelectorAll, try this:
const allkey = document.querySelectorAll(".key");