const mediaQueryList = window.matchMedia("(orientation: portrait)");Testing media queries programmatically / notebook
Testing media queries programmatically
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
if (mediaQueryList.matches) {
/* The viewport is currently in portrait orientation */
} else {
/* The viewport is not currently in portrait orientation, therefore landscape */
}// Create the query list.
const mediaQueryList = window.matchMedia("(orientation: portrait)");
// Define a callback function for the event listener.
function handleOrientationChange(mql) {
// …
}
// Run the orientation change handler once.
handleOrientationChange(mediaQueryList);
// Add the callback function as a listener to the query list.
mediaQueryList.addEventListener("change", handleOrientationChange);function handleOrientationChange(evt) {
if (evt.matches) {
/* The viewport is currently in portrait orientation */
} else {
/* The viewport is currently in landscape orientation */
}
}mediaQueryList.removeEventListener("change", handleOrientationChange);