Skip to content

Commit

Permalink
Allow a modal to be closed with the escape key. #27
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Erbe committed Jul 27, 2018
1 parent 8b5e3a0 commit 9aac4d2
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/plugins/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ class Modal {
if(this.closeButton && this.closable ) {
this.setupCloseEvent();
}

/**
* Create a bound version of our event escape event handler, this will
* allow us to remove the event listener later on.
*
* @type {Function}
*/
this.boundHandleEscapeClose = this.handleEscapeClose.bind(this);

document.addEventListener('keyup', this.boundHandleEscapeClose);
}

/**
Expand Down Expand Up @@ -94,6 +104,18 @@ class Modal {
this.close();
}

/**
* Close the modal if the Escape key is pressed
* @return {undefined}
*/
handleEscapeClose(event) {
let key = event.key || event.keyCode;

if(key === 'Escape' || key === 'Esc' || key === 27) {
this.close();
}
}

/**
* Destroy the message, removing the event listener, interval and element.
* @return {undefined}
Expand All @@ -103,6 +125,8 @@ class Modal {
this.closeButton.removeEventListener('click', this.handleCloseEvent.bind(this));
}

document.removeEventListener('keyup', this.boundHandleEscapeClose);

this.root = null;
this.closeButton = null;
}
Expand Down

0 comments on commit 9aac4d2

Please # to comment.