Search code examples
javascriptmodal-window

how to remove duplicate code from modalOverlay and closeBtn?


I have different modal windows, I added a close button but faced with duplicate code, how can I shorten the code for modalOverlay and closeBtn? and for some reason the second close button does not work, help pls https://jsfiddle.net/uza0jm8c/4/

enter code here

Solution

  • Your code added the click event only to the first button. Below code will make both buttons work:

    var closeBtn = document.getElementsByClassName("btn-close");
    
    for (var i = 0; i < closeBtn.length; i++) {
        closeBtn[i].addEventListener('click', (e) => {
            modalOverlay.classList.remove('modal-overlay--visible');
            modals.forEach((el) => {
                el.classList.remove('modal--visible');
            });
        });
    }