<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>