Guest User

Untitled

a guest
Jun 21st, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. //--------------------------------------------------------------
  2. // Modal
  3. //--------------------------------------------------------------
  4.  
  5. export const Modals = (function() {
  6.  
  7. function BuildModals() {
  8. let publicAPIs = {};
  9.  
  10. /**
  11. * Private Methods
  12. */
  13. function runModals() {
  14. const modals = [...document.querySelectorAll('[data-modal]')];
  15.  
  16. modals.forEach(modal => {
  17. const modalId = modal.getAttribute('data-modal');
  18. publicAPIs.modals[modalId] = modal
  19. });
  20.  
  21. // Open
  22. document.addEventListener('click', e => {
  23. // bail if not an a tag
  24. if (e.target.nodeName !== 'A') return;
  25.  
  26. // Bail if the hash is not formatted correctly
  27. if(!isTargetUrl(e.target.hash)) return;
  28.  
  29. const hashTarget = (e.target.hash).replace('#', '');
  30.  
  31. if(checkForModalId(hashTarget)) {
  32. e.preventDefault();
  33.  
  34. publicAPIs.openModal(hashTarget);
  35. }
  36. });
  37.  
  38. // Close
  39. document.addEventListener('click', e => {
  40. if (e.target.hasAttribute('data-close-modal')) {
  41. publicAPIs.closeAllModals();
  42. }
  43. });
  44. }
  45.  
  46. /**
  47. * Check if url is a target url with the #
  48. */
  49. function isTargetUrl(url) {
  50. const test = new RegExp(/^#/, 'gm');
  51.  
  52. return test.test(url);
  53. }
  54.  
  55. // Check if Modal is in the list of registered Modals
  56. function checkForModalId(id) {
  57. return publicAPIs.modals.hasOwnProperty(id);
  58. }
  59.  
  60. /**
  61. * Public APIs
  62. */
  63. publicAPIs.modals = {};
  64.  
  65. publicAPIs.openModal = function(modalId) {
  66. publicAPIs.modals[modalId].classList.add('is-active');
  67. }
  68.  
  69. publicAPIs.closeAllModals = function() {
  70. for (let modal in publicAPIs.modals) {
  71. publicAPIs.modals[modal]
  72. .classList.remove('is-active');
  73. }
  74. }
  75.  
  76. publicAPIs.init = function() {
  77. runModals();
  78. }
  79.  
  80. publicAPIs.init();
  81.  
  82. return publicAPIs;
  83. }
  84.  
  85. return BuildModals;
  86.  
  87. })(window, document);
Add Comment
Please, Sign In to add comment