Last active
April 16, 2020 16:35
-
-
Save baldore/631185cfb71b53b5fd3b7d7250ce99f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const values = { | |
sm: { | |
max: 599 | |
}, | |
md: { | |
min: 600, | |
max: 1023 | |
}, | |
lg: { | |
min: 1024, | |
max: 1799 | |
}, | |
xl: { | |
min: 1800 | |
} | |
} | |
export const breakpoints = { | |
sm: 'sm', | |
md: 'md', | |
lg: 'lg', | |
xl: 'xl' | |
} | |
export const medias = { | |
smOnly: window.matchMedia(`only screen and (max-width: ${values.sm.max}px)`), | |
mdOnly: window.matchMedia(`only screen and (min-width: ${values.md.min}px) and (max-width: ${values.md.max}px)`), | |
lgOnly: window.matchMedia(`only screen and (min-width: ${values.lg.min}px) and (max-width: ${values.lg.max}px)`), | |
xlOnly: window.matchMedia(`only screen and (min-width: ${values.xl.min}px)`) | |
} | |
/** | |
* Adds a listener that runs each time the device change between breakpoints. | |
* @param {function} callback Function to run on breakpoint change. | |
* @param {boolean} [callFirstTime=true] Defines if should call the callback the first time. | |
*/ | |
export function onBreakpointChange (callback, callFirstTime = true) { | |
const callbackIfMatches = e => e.matches && callback(getCurrentBreakpoint()) | |
if (callFirstTime) { | |
callback(getCurrentBreakpoint()) | |
} | |
medias.smOnly.addListener(callbackIfMatches) | |
medias.mdOnly.addListener(callbackIfMatches) | |
medias.lgOnly.addListener(callbackIfMatches) | |
medias.xlOnly.addListener(callbackIfMatches) | |
} | |
/** | |
* Returns the current breakpoint. | |
* @returns {string} Code of the breakpoint. | |
*/ | |
export function getCurrentBreakpoint () { | |
if (medias.smOnly.matches) { | |
return breakpoints.sm | |
} | |
if (medias.mdOnly.matches) { | |
return breakpoints.md | |
} | |
if (medias.lgOnly.matches) { | |
return breakpoints.lg | |
} | |
if (medias.xlOnly.matches) { | |
return breakpoints.xl | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment