Skip to content

Instantly share code, notes, and snippets.

@dpogni
Created August 15, 2019 18:22
Show Gist options
  • Select an option

  • Save dpogni/f053f50633e4c773f329170ae9af57cd to your computer and use it in GitHub Desktop.

Select an option

Save dpogni/f053f50633e4c773f329170ae9af57cd to your computer and use it in GitHub Desktop.
Resize and Throttling
/**
* 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);
}
};
}
import { throttle } from 'wherever';
function onWindowResize() {
//check mobile tablet etc do stuff
}
window.addEventListener('resize', throttle(onWindowResize));
/**
* 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