Skip to content

Instantly share code, notes, and snippets.

@andfinally
Last active April 11, 2016 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andfinally/0111e443ae319ffaad090f7603fc3027 to your computer and use it in GitHub Desktop.
Save andfinally/0111e443ae319ffaad090f7603fc3027 to your computer and use it in GitHub Desktop.
Breakpoint watcher - when a page has crossed a CSS breakpoint, calls a callback, passing an object representing the breakpoint you've left and an object representing the breakpoint you've entered
<html>
<head>
<title>-- == TEST == --</title>
</head>
<style>
body {
background: #FF1493;
}
@media screen and (min-width: 768px) {
body {
background: #228B22;
}
}
@media screen and (min-width: 1024px) {
body {
background: #00FFFF;
}
}
</style>
<body>
<script>
var breakpoints = [
{minWidth: 0, name: 'small'},
{minWidth: 768, name: 'medium'},
{minWidth: 1024, name: 'large'}
].reverse();
// When window size crosses breakpoint, callback is called with two arguments
// was - object - the breakpoint we've just left
// is - object - the breakpoint we've just entered
function breakpointWatcher(breakpoints, callback) {
var was = getCurrentBreakpoint();
console.log('STARTING BREAKPOINT ' + was.name);
window.onresize = debounce(resizeHandler, 100);
function resizeHandler() {
var is = getCurrentBreakpoint();
if (is.minWidth !== was.minWidth) {
callback(was, is);
} ;
was = is;
}
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function () {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args);
};
};
function getCurrentBreakpoint() {
var docWidth = getDocWidth();
for (var i = 0; i < breakpoints.length; i++) {
if (docWidth >= breakpoints[i].minWidth) {
return breakpoints[i];
}
}
}
function getDocWidth() {
return Math.max(document.documentElement["clientWidth"], document.body["scrollWidth"], document.documentElement["scrollWidth"], document.body["offsetWidth"], document.documentElement["offsetWidth"]);
}
}
breakpointWatcher(breakpoints, function (was, is) {
console.log('Left ' + was.name);
console.log('Entered ' + is.name);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment