xlfe
xlfe

Reputation: 148

matchMedia removeListener doesn't work?

I am trying to use the matchMedia / mediaQuery Web Api - I can successfully add a listener, but I am unable to remove the listener.

What am I missing?

This code demonstrates the problem - try printing the page - note you get TEST logged in the console even though you shouldn't...

var test=function(){
    console.log("TEST")
}

window.matchMedia('print').addListener(test);
window.matchMedia('print').removeListener(test);

I've tested and this occurs on both Chrome and Safari

Upvotes: 5

Views: 3063

Answers (1)

Josh Lee
Josh Lee

Reputation: 177624

You’re creating a new media query list each time, so you’re not able to remove the listener from the first query.

var m = window.matchMedia('print');
m.addListener(test);
m.removeListener(test);

Upvotes: 8

Related Questions