There's a polyfill added to Drupal 8 for matchMedia
and MediaQueryList
event listeners.
This polyfill allows you to add JavaScript event listeners to media queries, every time the media query state changes, your JavaScript function will be executed. The event will be triggered if the media query matches (starts to match), or if it doesn't match (stops to match).
Example
var x = window.matchMedia("(min-width: 600px)");
x.addListener(function (mql) {
console.log(mql);
console.log(mql.media + ': ' + mql.matches);
});
If you make your browser window smaller than 600px, the event will be fired once (mql.matches == false
). If you make it wider than 600px it will be fired again (mql.matches == true
).
Module
To be able to use this polyfill, your module's JavaScript must declare a dependency on this JavaScript library, or include it manually:
drupal_add_library('system', 'matchmedia');