Skip to content

Commit

Permalink
attach on window load to make sure that body is declared, see #1048
Browse files Browse the repository at this point in the history
  • Loading branch information
jessegreenberg committed Apr 23, 2020
1 parent f814a09 commit c4cd981
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions js/accessibility/KeyStateTracker.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,9 +310,6 @@ class KeyStateTracker {
*/
attachToBody() {
assert && assert( !this.attachedToBody, 'KeyStateTracker is already attached to body.' );
if ( !document.body ) {
throw new Error( 'Cant access body element until it is declared, run script later or in a timeout.' );
}

this.bodyKeydownListener = event => {
if ( this.blockTrustedEvents && event.isTrusted ) {
Expand All @@ -328,11 +325,17 @@ class KeyStateTracker {
this.keyupUpdate( event );
};

// attach with useCapture so that the keyStateTracker is up to date before the events dispatch within Scenery
document.body.addEventListener( 'keydown', this.bodyKeydownListener, true );
document.body.addEventListener( 'keyup', this.bodyKeyupListener, true );
// attach listeners on window load to ensure that the body is defined
const loadListener = event => {

// attach with useCapture so that the keyStateTracker is up to date before the events dispatch within Scenery
document.body.addEventListener( 'keydown', this.bodyKeydownListener, true );
document.body.addEventListener( 'keyup', this.bodyKeyupListener, true );
this.attachedToBody = true;

this.attachedToBody = true;
window.removeEventListener( 'load', loadListener );
};
window.addEventListener( 'load', loadListener );
}

/**
Expand Down

0 comments on commit c4cd981

Please sign in to comment.