Skip to content

Instantly share code, notes, and snippets.

@mindfullsilence
Last active September 28, 2017 17:54
Show Gist options
  • Save mindfullsilence/06db84f0992e165a3b01 to your computer and use it in GitHub Desktop.
Save mindfullsilence/06db84f0992e165a3b01 to your computer and use it in GitHub Desktop.
CSS media query in javascript using bootstrap classes
/**
* User: TimAnderson
* Date: 12/1/15
* Time: 1:25 PM
*/
/**
* Test responsive screen sizes by creating a visible-[screen]-block div. Passing multiple screen sizes will return true if one of them is true.
* See {@link http://codepen.io/mindfullsilence/pen/BjRJvN} for example usage.
* @requires jQuery
* @param {(...string|array)} className - The screen(s) to check against. In bootstrap, these are 'xs', 'sm', 'md', 'lg'.
* @returns {Boolean}
*/
const $ = require('jquery')
const mediaIs = function ( className ) {
var class_string = '',
$item,
visible;
var stringcheck = function(item) {
var allowed = ['xs', 'sm', 'md', 'lg'];
if(allowed.indexOf(item) === -1) {
console.warn('mediaIs: The string you passed ("' + item + '") does not match one of [' + allowed.join(',') + '], which are the bootstrap default screen sizes. Unless you have created a .visible-' + item + '-block class in your styles, this will likely return a false positive.');
console.trace();
}
};
if ( className instanceof Array ) {
className.forEach( function ( el, index ) {
if(typeof el === 'string') {
stringcheck(el);
class_string += 'visible-' + el.trim() + '-block ';
}
else {
console.error('mediaIs: Index ' + index + ' of your array must be a string. You passed in ' + typeof el + '.');
}
} )
}
else if ( arguments.length > 1 ) {
[].slice.call( arguments ).forEach( function ( el ) {
if ( typeof el === 'string' ) {
stringcheck( el );
class_string += 'visible-' + el.trim() + '-block ';
}
else {
console.error( 'mediaIs: ' + [].slice.call( arguments ).join( ', ' ) + ' cannot be used in this method because it is of type ' + typeof className );
return false;
}
} );
}
else if ( typeof className === 'string' ) {
stringcheck(className);
class_string += 'visible-' + className + '-block';
}
else {
console.error( 'mediaIs: ' + [].slice.call( arguments ).join( ', ' ) + ' cannot be used in this method because it is of type ' + typeof className + '.\nYou may use a string only.');
return false;
}
$item = $( '<div class="' + class_string + '"></div>' );
$( 'body' ).append( $item );
visible = ($item.css( 'display' ) != 'none');
$item.remove();
return visible;
};
module.exports = mediaIs
{
"name": "mediaIs",
"description": "Check the current screen size against bootstrap classes",
"version": "1.0.0",
"repositories": [
{
"type": "git",
"url": "https://gist.github.com/06db84f0992e165a3b01.git"
}
],
"licenses": [
{
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
}
],
"dependencies" : {
"jquery" : ">=2.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment