Skip to content

Instantly share code, notes, and snippets.

@joepuzzo
Created June 20, 2022 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joepuzzo/3b1eedc81941b7a4e01e6a5a47d10f10 to your computer and use it in GitHub Desktop.
Save joepuzzo/3b1eedc81941b7a4e01e6a5a47d10f10 to your computer and use it in GitHub Desktop.
Util functions for determining media size in browser
const mediaQueries = {
"phone-only": "(max-width: 599px)",
"tablet-portrait-only": "(min-width: 600px) and (max-width: 899px)",
"tablet-portrait-up": "(min-width: 600px)",
"tablet-landscape-only": "(min-width: 900px) and (max-width: 1199px)",
"tablet-landscape-up": "(min-width: 900px)",
"desktop-only": "(min-width: 1200px) and (max-width: 1799px)",
"desktop-up": "(min-width: 1200px)",
"desktop-large-up": "(min-width: 1800px)",
"density--2x": "only screen and (-o-min-device-pixel-ratio: 5/4), only screen and (-webkit-min-device-pixel-ratio: 1.25), only screen and (min-device-pixel-ratio: 1.25), only screen and (min-resolution: 1.25dppx)",
"density--3x": "only screen and (-o-min-device-pixel-ratio: 9/4), only screen and (-webkit-min-device-pixel-ratio: 2.25), only screen and (min-device-pixel-ratio: 2.25), only screen and (min-resolution: 2.25dppx)",
"density--4x": "only screen and (-o-min-device-pixel-ratio: 13/4), only screen and (-webkit-min-device-pixel-ratio: 3.25), only screen and (min-device-pixel-ratio: 3.25), only screen and (min-resolution: 3.25dppx)"
}
/**
* matchMediaQuery
*
* @param {*} query 'phone-only' | 'desktop-up', etc. See tokens/media.json for a complete list
* @returns a MediaQueryList for the matching query
*/
export const matchMediaQuery = (query) => window.matchMedia(mediaQueries[query]);
/**
* isMedia
* - Util function for matching the current window's media query
* @param query 'phone-only' | 'desktop-up', etc. See tokens/media.json for a complete list
* @returns true | false if the window is of the query's dimensions
*/
export const isMedia = (query) => matchMediaQuery(query).matches;
/**
* Query-specific utils
* @returns true if query is matched
*/
export const isPhoneOnly = () => isMedia('phone-only');
export const isTabletPortraitOnly = () => isMedia('tablet-portrait-only');
export const isTabletPortraitUp = () => isMedia('tablet-portrait-up');
export const isTabletLandscapeOnly = () => isMedia('tablet-landscape-only');
export const isTabletLandscapeUp = () => isMedia('tablet-landscape-up');
export const isDesktopOnly = () => isMedia('desktop-only');
export const isDesktopUp = () => isMedia('desktop-up');
export const isDesktopLargeUp = () => isMedia('desktop-large-up');
/**
* Density-specific utils
*/
export const isDensity2x = () => isMedia('density--2x');
export const isDensity3x = () => isMedia('density--3x');
export const isDensity4x = () => isMedia('density--4x');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment