Last active
February 21, 2017 14:18
-
-
Save vincentorback/503d907e65e00ce4086f to your computer and use it in GitHub Desktop.
Sync resizing event and breakpoints
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
/** | |
* 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); | |
} |
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
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