What would matchMedia("(min-width: 500px)").addListener(foo);
do? That is what does addListener()
function do here? Does it execute the function foo()
when the viewport width changes?

- 88,409
- 26
- 156
- 177

- 7,087
- 14
- 68
- 143
2 Answers
Yes, it executes foo
function
when the media query's evaluated result changes.
(from MDN)
In your case this means that if you start with a window with width greater that 500px and then you resize it to less than 500px, the function will execute. If you later resize it back to have width greater than 500px, the function will execute again.
The function is called with MediaQueryListEvent
as the first argument. It contains boolean matches
property which denotes if your media query currently matches the viewport.

- 88,409
- 26
- 156
- 177
-
1Isn't it quite similar to `onresize` event? I mean if we already have `window.onresize` then why do we need `addListener`? – user31782 May 07 '16 at 09:07
-
@user31782 You can use more complicated media queries, for example to require specific orientation or aspect ratio. See [Using media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) on MDN. – Michał Perłakowski May 07 '16 at 09:10
-
But we can use all these complicated media queries without `addListener` function too. What required is the `matchMedia` object and the `onresize` event handler. – user31782 May 07 '16 at 09:17
-
@user31782 That's true. I this it's just more convenient to use `matchMedia` with `addListener`. – Michał Perłakowski May 07 '16 at 09:47
The listener foo()
will be executed when the evaluation of the media query changes (either from true
to false
or from false
to true
.
There is an important difference between matchMedia(...).addEventListener(foo)
and window.onResize(foo)
. In the former, foo()
will only be executed when the evaluation of the media query changes. In the later, foo()
will be repeatedly executed every time the browser window changes size. If you are targeting specific breakpoints then you will need to test for these inside foo()
before executing other logic.
matchMedia(...).addEventListener(foo)
allows you to write logic in foo()
that is more focused without including additional logic (or other function calls) to test for browser dimension or other information that can be evaluated by a media query. There is also a potential performance gain from using matchMedia(...).addEventListener(foo)
over window.onResize(foo)
in that foo()
will be executed less frequently.
Disclaimer: I haven't done real performance comparisons between the two approaches. My assumption is based on the idea that an event handler that is not executed is faster than one that is. This does not, however, take into account any native differences between the two approaches.

- 21
- 6
-
Do you mean `matchMedia.addListener` ? cause `addEventListener` takes different arguments (type, then foo) – Julix May 17 '19 at 20:15