From 9aac4d23459ba300915d187d01c83486f4e58142 Mon Sep 17 00:00:00 2001 From: Thomas Erbe Date: Fri, 27 Jul 2018 21:20:48 +0100 Subject: [PATCH] Allow a modal to be closed with the escape key. #27 --- src/plugins/modal.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/plugins/modal.js b/src/plugins/modal.js index 2f9c202..668ce76 100644 --- a/src/plugins/modal.js +++ b/src/plugins/modal.js @@ -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); } /** @@ -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} @@ -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; }