JavaScript: Get notified in JavaScript when a media query status changes
Last updated: 12th May 2020You 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.