Home » Javascript » Javascript – Cannot read property 'addEventListener' of null in modal

Javascript – Cannot read property 'addEventListener' of null in modal

Posted by: admin July 12, 2018 Leave a comment

Questions:

I’m trying to implement some modals to my site. When I load the page in browser the following error appears in console: Uncaught TypeError: Cannot read property 'addEventListener' of null I’m using this code with this functions:

let ModalEffects = (function () {
    function init() {
        let overlay = document.querySelector('.md-overlay');
        [].slice.call(document.querySelectorAll('.md-trigger')).forEach(function (el, i) {
            let modal = document.querySelector('#' + el.getAttribute('data-modal')),
                close = modal.querySelector('.md-close');
            function removeModal(hasPerspective) {
                classie.remove(modal, 'md-show');
                if (hasPerspective) {
                    classie.remove(document.documentElement, 'md-perspective');
                }
            }
            function removeModalHandler() {
                removeModal(classie.has(el, 'md-setperspective'));
            }
            el.addEventListener('click', function (ev) {
                classie.add(modal, 'md-show');
                overlay.removeEventListener('click', removeModalHandler);
                overlay.addEventListener('click', removeModalHandler);
                if (classie.has(el, 'md-setperspective')) {
                    setTimeout(function () {
                        classie.add(document.documentElement, 'md-perspective');
                    }, 25);
                }
            });
            close.addEventListener('click', function (ev) {
                ev.stopPropagation();
                removeModalHandler();
            });
        });
    }
    init();
})();

My HTML:

<button class="md-trigger" data-modal="modal-1"></button>
<button class="md-trigger" data-modal="modal-2"></button>

<div class="md-modal md-effect-1" id="modal-1">
  <div class="md-content">
    <span>Some text</span>
  </div>
</div>

<div class="md-modal md-effect-1" id="modal-2">
  <div class="md-content">
    <span>Some text 2</span>
  </div>
</div>

Anyone can help me solve this? With that error, the modal does not work properly.

Thanks.

Answers: