Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 992
xlfe Avatar asked Mar 18 '23 12:03

xlfe


1 Answers

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);
like image 52
Josh Lee Avatar answered Mar 27 '23 19:03

Josh Lee