//--------------------------------------------------------------
// Modal
//--------------------------------------------------------------
export const Modals = (function() {
function BuildModals() {
let publicAPIs = {};
/**
* Private Methods
*/
function runModals() {
const modals = [...document.querySelectorAll('[data-modal]')];
modals.forEach(modal => {
const modalId = modal.getAttribute('data-modal');
publicAPIs.modals[modalId] = modal
});
// Open
document.addEventListener('click', e => {
// bail if not an a tag
if (e.target.nodeName !== 'A') return;
// Bail if the hash is not formatted correctly
if(!isTargetUrl(e.target.hash)) return;
const hashTarget = (e.target.hash).replace('#', '');
if(checkForModalId(hashTarget)) {
e.preventDefault();
publicAPIs.openModal(hashTarget);
}
});
// Close
document.addEventListener('click', e => {
if (e.target.hasAttribute('data-close-modal')) {
publicAPIs.closeAllModals();
}
});
}
/**
* Check if url is a target url with the #
*/
function isTargetUrl(url) {
const test = new RegExp(/^#/, 'gm');
return test.test(url);
}
// Check if Modal is in the list of registered Modals
function checkForModalId(id) {
return publicAPIs.modals.hasOwnProperty(id);
}
/**
* Public APIs
*/
publicAPIs.modals = {};
publicAPIs.openModal = function(modalId) {
publicAPIs.modals[modalId].classList.add('is-active');
}
publicAPIs.closeAllModals = function() {
for (let modal in publicAPIs.modals) {
publicAPIs.modals[modal]
.classList.remove('is-active');
}
}
publicAPIs.init = function() {
runModals();
}
publicAPIs.init();
return publicAPIs;
}
return BuildModals;
})(window, document);