Skip to content

Instantly share code, notes, and snippets.

@luigimannoni
Created November 14, 2015 11:24
Show Gist options
  • Save luigimannoni/f82fce1f00e69fab48cf to your computer and use it in GitHub Desktop.
Save luigimannoni/f82fce1f00e69fab48cf to your computer and use it in GitHub Desktop.
Stacked Modals
// 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment