javascriptaddeventlistenerremoveeventlistenermatchmedia

How to add removeEventListener in window.matchMedia?


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);

Solution

  • "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