Created
November 14, 2015 11:24
-
-
Save luigimannoni/f82fce1f00e69fab48cf to your computer and use it in GitHub Desktop.
Stacked Modals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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