Skip to content

Instantly share code, notes, and snippets.

@micah1701
Last active Nov 11, 2017
Embed
What would you like to do?
Register multiple "ESC" key handlers so hitting the escape key only does the most recently registered action. (requires jQuery)
var escEvents = new Array();
// If something needs to listen for the "ESC" key to be pressed, pass that functionality here
// eventName STRING a name for this event, like "myPopupDialog"
// eventFunction FUNCTION what to do when the user hits the escape key
function setEscEvent(eventName, eventFunction){
escEvents.push({ eventName: eventName, eventFunction: eventFunction });
}
// When an item doesn't need to listen for the "ESC" key anymore, remove it
// this is called automatically after escape is pressed, but if you no longer need to listen you can call it manually
// eventName STRING the name assigned to the event in setEscEvent()
function unsetEscEvent(eventName)
{
$.each(escEvents, function (index, value) {
console.log(value);
if (value['eventName'] == eventName)
{
escEvents.splice(index);
}
});
}
// When the "ESC" key is pressed, do the most recent registered function
// then unset this listener since the event is over
function runEscEvent()
{
var lastEvent = escEvents.length - 1;
eval(escEvents[lastEvent].eventFunction());
unsetEscEvent(escEvents[lastEvent].eventName);
}
// This is the listener for the escape key to be pressed
$(document).on( 'keyup', function ( event ){
event.preventDefault();
if (escEvents.length > 0 && event.keyCode === 27) {
runEscEvent();
}
} );
/* ************** */
// EXAMPLE USAGE:
function myPopup()
{
// ... code to open the popup
//if the user hits the escape key, close the popup
setEscEvent('popup',function () { closePopup() });
//if the user clicks the "close" button or anywhere outside the popup, close it.
//if your event doesn't have another way to close it (and the user has to press ESC) then this is OPTIONAL
$("#popup-close, #modal-background").on("click", function (e) {
closePopup(); // run the function to close the popup
unsetEscEvent('popup'); // manually unset the ESC key listener since we no longer need it
});
}
function closePopup()
{
// ...code to close the popup
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment