// Global variable, we use this to store DOM objects.
var modalStack = [];
// My function to create/open my modals.
function openModal() {
var modalHTML = '<div id="modal-'+modalStack.length+'" class="modal"><button onclick="openModal()">Open modal '+(modalStack.length+1)+'</button></div>'; // I populate the modal with my stuff and assign it an ID containing the current stack size.
document.body.insertAdjacentHTML( 'beforeend', modalHTML ); // Add into the body
modalStack.push( document.getElementById('modal-'+modalStack.length) ); // And push my DOM object I just created into the array.
}
// My ESC event listener
window.addEventListener('keyup', function(event) {
var lastIndex = modalStack.length-1; // This gets the last element on the stack.
if (event.keyCode == 27 && lastIndex >= 0) {
var thisModal = modalStack[ lastIndex ]; // Just to make sense, I could've called the removeChild directly from the array.
thisModal.parentNode.removeChild(thisModal); // Destroy the current element.
modalStack.pop(); // Remove the associated last DOM object from the array.
}
}, false);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.