Skip to content

Instantly share code, notes, and snippets.

@Sjeiti
Last active August 29, 2015 14:01
Show Gist options
  • Save Sjeiti/23b99c384173a5bfc90a to your computer and use it in GitHub Desktop.
Save Sjeiti/23b99c384173a5bfc90a to your computer and use it in GitHub Desktop.
Find breakPoints by searching through the document.styleSheets
/*global signals, CSSMediaRule*/
window.breakPoints = (function(signal){
'use strict';
window.addEventListener('load',function(){
var forEach = Array.prototype.forEach
,aSizes = [Number.MAX_VALUE]
,iSizes
,iCurrent = -1
;
// loop styleSheets, then cssRules, then media
forEach.apply(document.styleSheets,[function(styleSheet){
if (styleSheet.href!==null) {
forEach.apply(styleSheet.cssRules,[function(rule){
if (rule.constructor===CSSMediaRule) {
if (rule.media.length>0&&rule.media[0]===undefined) { // see: http://msdn.microsoft.com/en-us/library/ff460307(v=vs.85).aspx
findBreakpoint(rule.media.mediaText);
} else {
forEach.apply(rule.media,[function(medium){
findBreakpoint(medium);
}]);
}
}
}]);
}
}]);
aSizes.sort(function(a,b){return a>b?1:-1;});
iSizes = aSizes.length;
signal.current = iCurrent;
signal.points = aSizes;
if (iSizes!==0) {
window.addEventListener('resize',handleResize);
handleResize();
} else {
console.warn('No breakpoints found');
}
/**
* Searches string for breakpoint to add to the list.
* @param medium {string}
*/
function findBreakpoint(medium){
var aMatch = medium.match(/\(([^\)]+)\)/g);
aMatch&&aMatch.forEach(function(match){
var aWidth = match.match(/width/)
,aDigit = match.match(/\d+/)
,bMax = !!match.match(/max/)
;
if (aWidth&&aDigit) {
var iSize = parseInt(aDigit.pop()) + (bMax?1:0);
if (aSizes.indexOf(iSize)===-1) aSizes.push(iSize);
}
});
}
/**
* Handle resize event to check which breakpoint we are at.
* Dispatches signal when breakpoint changes
*/
function handleResize(){
var iWindowWidth = window.innerWidth;
var iCheckSize = aSizes[0];
for (var i=0;i<iSizes;i++) {
iCheckSize = aSizes[i];
if (iWindowWidth<iCheckSize) {
break;
}
}
if (iCheckSize!==iCurrent) {
var iOld = iCurrent;
iCurrent = iCheckSize;
signal.current = iCurrent;
signal.dispatch(iCurrent,iOld);
}
}
},false);
return signal;
})(new signals.Signal());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment