Skip to content

Instantly share code, notes, and snippets.

@oddvalue
Created September 21, 2018 10:32
Show Gist options
  • Save oddvalue/6238eb3d4e0a4c68353d9e5977ad29c7 to your computer and use it in GitHub Desktop.
Save oddvalue/6238eb3d4e0a4c68353d9e5977ad29c7 to your computer and use it in GitHub Desktop.
Get CSS breakpoints in to JS
/**
* Get current CSS breakpoint from doc body pseudo element
* Fires custom event 'breakpoint-changed' every time a new breakpoint is hit
*
* @type {Object}
* {
* current: {string} current breakpoint,
* previous: {string} previous breakpoint,
* }
*/
import resize from './_window-resize';
export default (() => {
const breakpoint = {
current: null,
previous: null,
};
breakpoint.refreshValue = () => {
breakpoint.current = window.getComputedStyle(document.body, ':before').getPropertyValue('content').replace(/"/g, '');
};
breakpoint.refreshValue();
const refreshBreakpoint = () => {
breakpoint.refreshValue();
if (breakpoint.current !== breakpoint.previous) {
const breakpointChangedEvent = new CustomEvent('breakpoint-changed', {
detail: breakpoint,
});
document.body.dispatchEvent(breakpointChangedEvent);
}
breakpoint.previous = breakpoint.current;
};
resize.listen(refreshBreakpoint);
return breakpoint;
})();
/**
* Set the current breakpoint name as the content of the doc body's
* before pseudo element
*/
body {
&::before {
display: none;
content: 'mobile';
@if (variable-exists(mq-breakpoints)) {
@each $bp-name, $bp-value in $mq-breakpoints {
@include mq($from: $bp-name) {
content: '#{$bp-name}';
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment