«   Previous tip Next tip   »

JavaScript: Get notified in JavaScript when a media query status changes

Last updated: 12th May 2020
Get notified in JavaScript when a media query status changes

You can watch for changes on media queries with the following JavaScript code:

window.matchMedia('(max-height: 150px)')
    .addListener(console.log)

As a response, you get a MediaQueryListEvent which, in addition to including the original media query string, contains a property named matches which specifies whether or not the media query applies to the current page.

As a use case: Imagine you're doing JavaScript animation which factors in the device pixel ratio. If the user drags the browser window to their second screen (with a different pixel density), you can observe for such changes and update the animation accordingly.

See the MDN Docs for more info.

«   Previous tip Next tip   »

Sign up to receive a developer tip, in the form of a gif, in your inbox each week