Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (() => {
  2.   const body = document.querySelector('body')
  3.   const modalButtons = document.querySelectorAll('button[data-toggle="modal"]')
  4.  
  5.   for (const button of modalButtons) button.onclick = () => openModal(button)
  6.  
  7.   function openModal(button) {
  8.     const modalId = button.getAttribute('data-target')
  9.     const modal = document.getElementById(modalId)
  10.  
  11.     body.classList.add('modal-open')
  12.     const fadeEffectDiv = document.createElement('div')
  13.     fadeEffectDiv.className = 'modal-backdrop fade show'
  14.     body.appendChild(fadeEffectDiv)
  15.  
  16.     modal.classList.add('show')
  17.     modal.style.display = 'block'
  18.  
  19.     const outsideClickHandler = handleClickOutside(modal, fadeEffectDiv)
  20.  
  21.     const closeButtons = modal.querySelectorAll('button[data-dismiss="modal"]')
  22.     for (const button of closeButtons) button.onclick = () => closeModal(modal, fadeEffectDiv, outsideClickHandler)
  23.  
  24.   }
  25.  
  26.   function handleClickOutside(modal, fadeEffectDiv) {
  27.     const handler = event => {
  28.       const content = modal.querySelector('.modal-content')
  29.       const shouldCloseModal = !content.contains(event.target)
  30.  
  31.       if (shouldCloseModal) {
  32.         closeModal(modal, fadeEffectDiv, handler)
  33.       }
  34.     }
  35.     document.addEventListener('click', handler , { capture: true })
  36.  
  37.     return handler
  38.   }
  39.  
  40.   function closeModal(modal, fadeEffectDiv, outsideClickHandler) {
  41.     body.classList.remove('modal-open')
  42.     body.removeChild(fadeEffectDiv)
  43.  
  44.     modal.classList.remove('show')
  45.     modal.style.display = 'none'
  46.  
  47.     document.removeEventListener('click', outsideClickHandler, { capture: true })
  48.   }
  49.  
  50. })()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement