Skip to content

Instantly share code, notes, and snippets.

@vincentorback
Last active February 21, 2017 14:18
Show Gist options
  • Save vincentorback/503d907e65e00ce4086f to your computer and use it in GitHub Desktop.
Save vincentorback/503d907e65e00ce4086f to your computer and use it in GitHub Desktop.
Sync resizing event and breakpoints
/**
* Dependencies
*/
const breakpoints = {
xs: 300,
sm: 600,
md: 800,
lg: 1200,
xl: 1600
};
let callbacks = [];
let running = false;
export function isAbove (val) {
val = breakpoints[val] || val;
return getViewportWidth() > val;
}
export function onResize (callback) {
if (callback) {
if (!callbacks.length) {
window.addEventListener('resize', debounce(() => {
resize();
}, 500));
}
callbacks.push(callback);
}
}
function resize () {
if (!running && callbacks.length) {
running = true;
runCallbacks();
}
}
function runCallbacks() {
callbacks.forEach(function(callback) {
callback();
});
running = false;
}
function debounce(fn, wait) {
let timeout;
return function () {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, arguments), (wait || 1));
};
}
function getViewportWidth() {
return Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
import { isAbove, onResize } from 'breakpoints';
onResize(() => {
if (isAbove('md')) {
// Do something!
} else if (!isAbove(340)) {
// Do something else!
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment