Importing CSS breakpoints into JS

HTML
<p><a href="https://www.lullabot.com/articles/importing-css-breakpoints-into-javascript">Read the whole article</a> by Mike Herchel</p> <p>To get the breakpoint value as a number instead of a text string:<br> use <code>.valuesAsNumber</code> in the breakpoint.refreshValue function, as well as in the if statements. Remember to also change the <code>content:'device'</code> lines to contain the numbers (for example <code>content:'700'</code>)in scss.</p> <p>Having the breakpoints as numbers means it'll be easier to use comparing operators for when something needs to encompass multiple breakpoints.</p>
SCSS
/** * These values will not show up in content, but can be * queried by JavaScript to know which breakpoint is active. * Add or remove as many breakpoints as you like. */ body:before { content: "smartphone"; display: none; /* Prevent from displaying. */ } @media (min-width: 700px) { body:before { content: "tablet"; } } @media (min-width: 1100px) { body:before { content: "desktop"; } }
JAVASCRIPT
var breakpoint = {}; breakpoint.refreshValue = function () { this.value = window.getComputedStyle(document.querySelector('body'), ':before').getPropertyValue('content').replace(/\"/g, ''); }; $(window).resize(function () { breakpoint.refreshValue(); }).resize(); if (breakpoint.value == 'tablet') { console.log('Tablet breakpoint'); } else { console.log('Some other breakpoint'); }
Expand for more options Login