Skip to content

Instantly share code, notes, and snippets.

@frankIT
Created October 15, 2016 22:40
Show Gist options
  • Save frankIT/64a3f1a6091e92a93aded135febc66be to your computer and use it in GitHub Desktop.
Save frankIT/64a3f1a6091e92a93aded135febc66be to your computer and use it in GitHub Desktop.
Just a JS function to check if the viewport matches the guessed bootstrap grid option.
/*
* Just a JS function to check if the viewport matches the guessed bootstrap grid option.
* It uses the modern matchMedia object passing the same media query that bootstrap use, in both v3 or 4.
* Otherwise falls back using the standard window object.
* I often saw using the screen object for the same purpose,
* but it behaves strangely in extended desktop layouts with multiple monitors.
* Note that window.innerWidth instead, should not be used from within frames.
*/
function isViewport(bsSelector)
{
BSversion = 3;
// http://getbootstrap.com/css/#grid-options
// https://v4-alpha.getbootstrap.com/layout/grid/#grid-options
width = {
xs: { min: 0, max: (BSversion < 4 ? 768 : 544) },
sm: { min: (BSversion < 4 ? 768 : 544), max: (BSversion < 4 ? 992 : 768) },
md: { min: (BSversion < 4 ? 992 : 768), max: (BSversion < 4 ? 1200 : 992) },
lg: { min: (BSversion < 4 ? 1200 : 992), max: (BSversion < 4 ? 0 : 1200) }
};
if( BSversion > 3 )
width['xl'] = { min: 1200, max: 0 };
largest = BSversion < 4 ? 'lg' : 'xl';
if( typeof width[bsSelector] === 'undefined' )
return false;
if( window.matchMedia )
{
mq = window.matchMedia(
( width[bsSelector].min > 0 ? '(min-width: '+ width[bsSelector].min +'px)' : '' ) +
( bsSelector != 'xs' && bsSelector != largest ? ' and ' : '' ) +
( width[bsSelector].max > 0 ? '(max-width: '+ width[bsSelector].max +'px)' : '' )
);
return mq.matches;
}
else
{ // fallback
// http://www.w3schools.com/jsref/prop_win_innerheight.asp
currentWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
switch( bsSelector ){
case 'xs':
if(currentWidth < width[bsSelector].max)
return true;
break;
case largest:
if(currentWidth > width[bsSelector].min)
return true;
break;
default:
if( currentWidth > width[bsSelector].min &&
currentWidth < width[bsSelector].max )
return true;
break;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment