Skip to content

Instantly share code, notes, and snippets.

@leandrowd
Last active August 29, 2015 14:14
Show Gist options
  • Save leandrowd/0650ec9fb5812819d7e1 to your computer and use it in GitHub Desktop.
Save leandrowd/0650ec9fb5812819d7e1 to your computer and use it in GitHub Desktop.
Breakpoints css + javascript

Breakpoint detector

How to use

  • Add all snippets to your source (css, js);
  • Invoke the mixin inside your css @include breakpoints-for-javascript;;
  • Call the function breakpoint() and test the result against the strings (mobile|tablet|desktop|large);

i.e: breakpoint() === 'mobile'

$tablet-width: 768px;
$desktop-width: 960px;
$large-width: 1280px;
/**
* Breakpoints mobile first
*/
@mixin tablet {
@media (min-width: #{$tablet-width}) {
@content;
}
}
@mixin desktop {
@media (min-width: #{$desktop-width}) {
@content;
}
}
@mixin large {
@media (min-width: #{$large-width}) {
@content;
}
}
/**
* Breakpoints exclusives
*/
@mixin only-mobile {
@media (max-width: #{$tablet-width}) {
@content;
}
}
@mixin only-tablet {
@media (min-width: #{$tablet-width}) and (max-width: #{$desktop-width}) {
@content;
}
}
@mixin only-desktop {
@media (min-width: #{$desktop-width}) and (max-width: #{$large-width}) {
@content;
}
}
/**
* Snippet to detect breakpoint using javascript
*/
@mixin breakpoints-for-javascript {
.breakpoint-detector {
display: none;
&.mobile {
@include only-mobile {display: block;}
}
&.tablet {
@include only-tablet {display: block;}
}
&.desktop {
@include only-desktop {display: block}
}
&.large {
@include large {display: block}
}
}
}
var breakpointClassName = 'breakpoint-detector';
var createMarkup = function () {
var breakpoints = ['mobile', 'tablet', 'desktop', 'large'];
function createDiv (breakpoint) {
var div = document.createElement('div');
div.className = [breakpointClassName, breakpoint].join(' ');
div.dataset.breakpoint = breakpoint;
return div;
}
breakpoints.forEach( function (item) {
document.body.appendChild(createDiv(item));
});
}
module.exports = function() {
var breakpointElements = document.querySelectorAll('.' + breakpointClassName);
if (!breakpointElements.length) {
createMarkup();
breakpointElements = document.querySelectorAll('.' + breakpointClassName);
}
var arr = Array.prototype.slice.apply(breakpointElements);
arr = arr.filter(function(item){
// if there is no offset parent, the element is hidden
return item.offsetParent;
})
if (arr.length !== 1) {
throw("Something is wrong on the configuration. Check the html and css to see if you have the correct rules");
}
return arr[0].dataset.breakpoint;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment