1

I was able to get an idea on how to close a modal window when clicking outside, but I am having issues to have it working when trying to have links inside the modal window.

I created a small code in Codepen to illustrate my point:

https://codepen.io/neotriz/pen/MRwLem

window.addEventListener('load', setup);

const get = document.getElementById.bind(document);
const query = document.querySelector.bind(document);

function setup() {

  let modalRoot = get('modal-root');
  let button = get('modal-opener');
  let modal = query('.modal');

  modalRoot.addEventListener('click', rootClick);
  button.addEventListener('click', openModal);
  modal.addEventListener('click', modalClick);

  function rootClick() {
    modalRoot.classList.remove('visible');
  }

  function openModal() {
    modalRoot.classList.add('visible');
  }

  function modalClick(e) {
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    return false;
  }

}
Alejandro
  • 2,266
  • 6
  • 35
  • 63

1 Answers1

1

remove e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation();from modalClick . Thats the reason you are not able to click on inside links.

and modify the function rootClick

function rootClick(event) {
          if (!(modal == event.target || modal.contains(event.target))) {
    modalRoot.classList.remove('visible');
          }
  }

Codepen : https://codepen.io/anon/pen/ZZGwRr

dagalti
  • 1,868
  • 1
  • 13
  • 15