intRG
intRG

Reputation: 45

Memory leak with addeventlistener()

I have a modal box which opens on a button click, when the modal is visible, if the area outside the content box is clicked, then the modal should disappear.

The issue i'm having is that my modal keeps creating the modal and not being completely removed, thus creating a memory leak.

The class show-login-modal handles the visibility of the modal.

let x = 1;

function LoginPopup(){

    let modal = document.getElementById('modal');

    modal.classList.add('show-login-modal');

    let xx = x++;

    function _removeModal() {
        modal.classList.remove('show-login-modal');
        modal.removeEventListener("click", this);
    }

    modal.addEventListener('click', function(event) {
        console.log(xx);
        if (event.target === modal) {
            _removeModal();
         } 
     });
}

I included the console.log for reference.

What is the best way to fix this?

Upvotes: 0

Views: 1196

Answers (1)

jmcgriz
jmcgriz

Reputation: 3358

removeEventListener is being used incorrectly, it needs to be invoked with a named function. So, in your case, you'd want to move the event target detection inside of _removeModal

function _removeModal(event){ if (event.target === this){ ... modal.removeEventListener('click', _removeModal)} }

modal.addEventListener('click', _removeModal)

Upvotes: 2

Related Questions