Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active February 19, 2019 08:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/6366121 to your computer and use it in GitHub Desktop.
Save branneman/6366121 to your computer and use it in GitHub Desktop.
JavaScript - CSS breakpoint Sync
/**
* Set the breakpoints as a font-family and pseudo element.
* This way JavaScript can read the current active breakpoint.
*/
head {
font-family: 'no-breakpoint';
}
body:after {
display: none;
content: 'no-breakpoint';
}
@include respond-min($breakpoint-a) {
head { font-family: 'breakpoint-a'; }
body:after { content: 'breakpoint-a'; }
}
@include respond-min($breakpoint-b) {
head { font-family: 'breakpoint-b'; }
body:after { content: 'breakpoint-b'; }
}
@include respond-min($breakpoint-c) {
head { font-family: 'breakpoint-c'; }
body:after { content: 'breakpoint-c'; }
}
/**
* Returns the active named breakpoint, or false if none is found.
*
* @see https://github.com/bjankord/Media-Query-Sync
*/
function getActiveBreakPoint() {
var activeMQ;
// Fix for Opera issue when using font-family to store value
if (window.opera) {
activeMQ = window.getComputedStyle(document.body, ':after').getPropertyValue('content');
}
// For all other modern browsers
else if (window.getComputedStyle) {
activeMQ = window.getComputedStyle(document.head, null).getPropertyValue('font-family');
}
// For oldIE
else {
// Use .getCompStyle instead of .getComputedStyle so above check for window.getComputedStyle never fires true for old browsers
window.getCompStyle = function(el, pseudo) {
this.el = el;
this.getPropertyValue = function(prop) {
var re = /(\-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
};
return this;
};
var compStyle = window.getCompStyle(document.getElementsByTagName('head')[0], '');
activeMQ = compStyle.getPropertyValue('font-family');
}
activeMQ = activeMQ
.replace(/"/g, '')
.replace(/'/g, '');
return activeMQ;
}
@AndreKelling
Copy link

just checked that this is a little performance issue as it forces a 'Recalculate Style' in the JS main thread. which can get costly if used often.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment