Bootstrap Viewport Detect - jQuery Plugin

Wednesday, December 18, 2013

I've been using the Bootstrap front-end framework for a little while now and have been enjoying the simplicity with which I can construct clean (if generic) looking web sites. Its native responsive design is fantastic but not perfect. I encountered a problem in which the display of my interface looked good in the "large", "medium" and "x-small" viewports but looked poor in the "small" viewport. My intended solution involved more than could be accomplished with Bootstrap's extremely useful .visible-* and .hidden-* classes and so I needed a way, in javascript, to determine the current viewport. To this end I wrote this small jQuery plugin. It works like a jQuery utility function and can either simply return the current viewport, or call a function whenever the viewport changes.


First, include the jQuery library (which you're already doing), then include the viewportDetect library.

<script type="text/javascript" src="jQuery.js"></script> 
<script type="text/javascript" src="viewportDetect.js"></script> 

Whenever you want to know what the current viewport is, just query the function like so. It will return a short string corresponding to the current viewport ("xs", "sm", "md", or "lg");

var viewport = $.viewportDetect();

A more useful approach is to register a callback function. Whenever the viewport changes the callback function will be called. In addition to the current viewport the function also receives the previous viewport. It may sometimes be useful to know if the viewport is expanding or contracting.

$.viewportDetect(function (currentViewport, previousViewport) {
    alert("viewport changed from " + previousViewport+ " to " + currentViewport);
< Previous: Broken Foot 4 - Six Week Update <
> Next: Surface Pro 2 Wireless Adapter Fixed >

< Preceding: MOBIeditor <
> Following: Strafe >
Add a Comment


your name
your email (optional)