If you need to be aware of changes to the evaluated result of the query on an ongoing basis, it's more efficient to register a listener than to poll the query's result. To do this, call the addEventListener() method on the MediaQueryList object, with a callback function to invoke when the media query status changes (e.g., the media query test goes from true to false):
const mediaQueryList = window.matchMedia("(orientation: portrait)");
function handleOrientationChange(mql) {
}
handleOrientationChange(mediaQueryList);
mediaQueryList.addEventListener('change', handleOrientationChange);
This code creates the orientation-testing media query list, then adds an event listener to it. After defining the listener, we also call the listener directly. This makes our listener perform adjustments based on the current device orientation; otherwise, our code might assume the device is in portrait mode at startup, even if it's actually in landscape mode.
The handleOrientationChange() function would look at the result of the query and handle whatever we need to do on an orientation change:
function handleOrientationChange(evt) {
if (evt.matches) {
} else {
}
}
Above, we define the parameter as evt — an event object. This makes sense because newer implementations of MediaQueryList handle event listeners in a standard way. They no longer use the unusual MediaQueryListListener mechanism, but a standard event listener setup, passing an event object of type MediaQueryListEvent as the argument to the callback function.
This event object also includes the media and matches properties, so you can query these features of the MediaQueryList by directly accessing it, or accessing the event object.