1

I would like to dispatch onKeyDown events from a body element too a div inside of the body.

I am using React and have tried adding an onKeyDown event listener to my body tag in the componentDidMount function of my React component.

componentDidMount() {
    document.getElementById("main-content").onkeydown = event => {
        document.getElementById("Keyboard").dispatchEvent(event);
    }
}

I expected the keydown event to be dispatched to the Keyboard component, but instead I receive the error listed below.

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.

Any help would be appreciated!

1 Answer 1

0

Can you not hardcode it onto your div element?
Use this question as reference if you can.

If you can't harcode it maybe try this:

    document.querySelector('#yourDiv').addEventListener('keydown', function (event) {
      console.log(event.key) //Change this to whatever you want it to do
    })

Then in your HTML give your div a tabindex="0" property.

The tabindex property:

tabindex="0" allows a non-form/link/object element to be placed in the default navigation order, allowing any element to be focusable and trigger interaction.

More info here

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, the question you linked worked! I tried hardcoding it, but I forgot to set tabIndex="0".
Glad I could help! I fell for the same problem before

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.