Skip to content

Instantly share code, notes, and snippets.

@toddzebert
Last active February 10, 2017 06:53
Show Gist options
  • Save toddzebert/7283fcf9590bb8e43c116148ad059686 to your computer and use it in GitHub Desktop.
Save toddzebert/7283fcf9590bb8e43c116148ad059686 to your computer and use it in GitHub Desktop.
Sharing CSS breakpoints with JavaScript - JavaScript
// see https://www.lullabot.com/articles/importing-css-breakpoints-into-javascript
// module pattern
var bpExport = (function (bpExport) {
// this will create a closure
bpExport.breakpoint = function(sel) {
// define private state
var state = null;
var callbacks = [];
var selector = sel;
// private set the state
function setState () {
return window.getComputedStyle(document.querySelector(selector), ':before')
.getPropertyValue('content')
.replace(/['"]/g, '');
}
// do initial state set
state = setState();
var bp = {};
// public method to refresh, although usually called as debounced window resize cb
bp.refresh = function () {
state = setState();
callbacks.forEach(function(cb) {
cb(state);
});
};
// provide this public method with a callback and it will be called with bp setting on resize
bp.onChange = function (cb) {
if (cb && typeof(cb) === "function") {
// call the cb with initial state
cb(state);
// add to list for future cb's
callbacks.push(cb);
}
};
// public method to get the state
bp.get = function () {
return state;
};
// setup on window resize callback
// using underscore's debounce but use whatever you'd like
window.addEventListener("resize", _.debounce(bp.refresh.bind(bp), 75));
return bp;
};
return bpExport;
})(bpExport || {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment