Skip to content Skip to sidebar Skip to footer

Functional Javascript Programming - Making A Modal, A Popup, And Refactoring It

I'm using ES5. I'm learning JavaScript. I did this modal, but I want to re-factor the code that's there, I'm pretty sure there is a better way to do this. If I add 5modals, how wil

Solution 1:

You could use closures through inner functions:

  function createModal() {
   //Variables
    var modal = document.querySelector('.modal');
    var modalBtn = document.querySelector('.modal-btn');
    var modalCloseBtn = document.querySelector('.modal__close');
    var body = document.querySelector('body');
    var modalOverlay = document.createElement('div');
    modalOverlay.className = 'modal-overlay';

    function openModal(e) {
       e.preventDefault();
       modalOverlay.classList.add('is-open');
       modal.classList.add('is-open');
       document.body.appendChild(modalOverlay);
    }

    function closeModal(e) {
     modalOverlay.classList.remove('is-open');
     modal.classList.remove('is-open');
     document.body.removeNode(modalOverlay);
    }

    modalCloseBtn.addEventListener('click', closeModal);
    modalOverlay.addEventListener('click', closeModal);
    modalBtn.addEventListener('click', openModal);

 }

 window.onclick = () => {
    createModal();
    createModal();
 };

Post a Comment for "Functional Javascript Programming - Making A Modal, A Popup, And Refactoring It"