I am creating a Hangman game with a virtual keypad and a form input section where users can guess the entire word.
I am able to add a 'keydown' event listener to the document, but I DO NOT want want the 'keydown' event to fire off if I am typing into the input field.
Here is how I've added the event listener.
document.addEventListener('keydown', handleKeyDown);
Here is the form input.
<form onSubmit={e => onSubmit(e)}>
<div className="input-group">
<input
type="text"
className="form-control"
name="letter"
placeholder="Guess the word"
value={formWord}
onChange={e => setFormWord(e.target.value.toUpperCase())}
disabled={disabled}
/>
<div className="input-group-append">
<button
className="btn text-white"
type="submit"
disabled={disabled}
>
<i className="far fa-arrow-alt-circle-right" /> Go!
</button>
</div>
</div>
</form>
I've already tried using document.getElementsByTagName[0].removeEventListener('keydown', handleKeyDown)
, but that's not working. I'm assuming that's because the event listener was added onto the actual document instead of the element.
Please help!
I am creating a Hangman game with a virtual keypad and a form input section where users can guess the entire word.
I am able to add a 'keydown' event listener to the document, but I DO NOT want want the 'keydown' event to fire off if I am typing into the input field.
Here is how I've added the event listener.
document.addEventListener('keydown', handleKeyDown);
Here is the form input.
<form onSubmit={e => onSubmit(e)}>
<div className="input-group">
<input
type="text"
className="form-control"
name="letter"
placeholder="Guess the word"
value={formWord}
onChange={e => setFormWord(e.target.value.toUpperCase())}
disabled={disabled}
/>
<div className="input-group-append">
<button
className="btn text-white"
type="submit"
disabled={disabled}
>
<i className="far fa-arrow-alt-circle-right" /> Go!
</button>
</div>
</div>
</form>
I've already tried using document.getElementsByTagName[0].removeEventListener('keydown', handleKeyDown)
, but that's not working. I'm assuming that's because the event listener was added onto the actual document instead of the element.
Please help!
Share Improve this question asked Sep 28, 2019 at 22:24 Sup3r DSup3r D 1472 silver badges12 bronze badges1 Answer
Reset to default 9Inside handleKeyDown
, only execute the body of the function if the event.target
does not match the input field, eg:
const handleKeyDown = (event) => {
if (event.target.matches('[name="letter"]')) {
return;
}
// rest of function body
};