Created
August 15, 2019 18:22
-
-
Save dpogni/f053f50633e4c773f329170ae9af57cd to your computer and use it in GitHub Desktop.
Resize and Throttling
This file contains hidden or 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
| /** | |
| * Throttle Handler | |
| * @param {function} callback | |
| * @param {number} limit (ms) | |
| */ | |
| export function throttle (callback, limit = 100) { | |
| let wait = false; | |
| return function throttleReturn(...args) { | |
| if (!wait) { | |
| callback.apply(null, ...args); | |
| wait = true; | |
| setTimeout(() => { | |
| wait = false; | |
| }, limit); | |
| } | |
| }; | |
| } |
This file contains hidden or 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
| import { throttle } from 'wherever'; | |
| function onWindowResize() { | |
| //check mobile tablet etc do stuff | |
| } | |
| window.addEventListener('resize', throttle(onWindowResize)); |
This file contains hidden or 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
| /** | |
| * Constants | |
| */ | |
| // Breakpoints | |
| export const BREAKPOINTS = { | |
| XS: 480, | |
| SM: 768, | |
| MD: 1024, | |
| LG: 1280, | |
| XL: 1440, | |
| }; | |
| // Get a Breakpoint (subtracts 1px for easier conditionals) | |
| export const GET_BREAKPOINT = { | |
| XS: () => BREAKPOINTS.XS - 1, | |
| SM: () => BREAKPOINTS.SM - 1, | |
| MD: () => BREAKPOINTS.MD - 1, | |
| LG: () => BREAKPOINTS.LG - 1, | |
| XL: () => BREAKPOINTS.XL - 1, | |
| }; | |
| // Functions to Check Breakpoints | |
| export function isMobile() { | |
| return window.innerWidth <= BREAKPOINTS.SM; | |
| } | |
| export function isTablet() { | |
| return (window.innerWidth <= BREAKPOINTS.MD) && window.innerWidth > GET_BREAKPOINT.SM(); | |
| } | |
| export function isDesktop() { | |
| return window.innerWidth > BREAKPOINTS.MD; | |
| } | |
| export function isMobileOrTablet() { | |
| return isMobile() || isTablet(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment