Bbabis
Bbabis

Reputation: 195

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

Upvotes: 3

Views: 1952

Answers (3)

aggregate1166877
aggregate1166877

Reputation: 3150

For anyone who specifically landed here because they were unable to remove a listener from matchMedia, I thought I'd add some details.

This is incorrect:

// Add listener
window
  .matchMedia(yourQuery)
  .addEventListener('change', yourHandlerFunction);

// Remove listener
window
  .matchMedia(yourQuery)
  .removeEventListener('change', yourHandlerFunction);

This is the correct way:

// Create the media matcher:
const mediaWatcher = window.matchMedia(yourQuery);

// Add the listener
mediaWatcher
  .addEventListener('change', yourHandlerFunction);

// Remove the listener
mediaWatcher
  .removeEventListener('change', yourHandlerFunction);

Upvotes: 1

Chiel
Chiel

Reputation: 1

x.removeListener(customFunction)

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

Upvotes: 0

Robert
Robert

Reputation: 2753

"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

Upvotes: 1

Related Questions