How to add removeEventListener in window.matchMedia?

1.5k Views Asked by At

Here is my problem:

I want to have an "addEventListener" click method only for browser size smaller than "400px". But when we resize the browser, I want to remove this method.

The format of my code is below. If I grow up the browser over 400px I continue to have the method. I want your help.

function customFunction(x) {

    var cardClick = document.getElementsByClassName("card");
    var inner = document.getElementsByClassName("card-inner");

    if (x.matches) {

        cardClick[0].addEventListener("click", cardFunction);

        function cardFunction() {
            // some code
            // inner[0].style......
        }

    } else {

        cardClick[0].removeEventListener("click", cardFunction);

    }
}

var x = window.matchMedia("(max-width: 400px)");
customFunction(x);
x.addListener(customFunction);
2

There are 2 best solutions below

1
Robert On BEST ANSWER

"Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect."

You define new version of card Function each time you call customFunctions so you can't detach it from element because is not the same function that you attach.

function cardFunction() {
   // some code
   // inner[0].style......
}

function customFunction(x) {

    var cardClick = document.getElementsByClassName("card");
    var inner = document.getElementsByClassName("card-inner");

    if (x.matches) {
        cardClick[0].addEventListener("click", cardFunction);

    } else {
        cardClick[0].removeEventListener("click", cardFunction);
    }
}

var x = window.matchMedia("(max-width: 400px)");
customFunction(x);
x.addListener(customFunction);
javascript
1
Chiel On
x.removeListener(customFunction)

check example here: https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/removeListener