Skip to content

Instantly share code, notes, and snippets.

@clecidor
Created March 19, 2015 15:10
Show Gist options
  • Save clecidor/ac40dfdee44c9e101a2a to your computer and use it in GitHub Desktop.
Save clecidor/ac40dfdee44c9e101a2a to your computer and use it in GitHub Desktop.
jquery.viewports.js adds css classes to <body> element based on browser's viewport size
(function($) {
if (!$) return; // bail if no jQuery
function initViewportJs() {
var bodyElement = $('body');
function checkViewportJS(evt) {
var bodyWidth = parseInt(bodyElement.css('width'));
if (!bodyWidth) return false;
bodyElement
.addClass('viewportjs-enabled')
.removeClass('viewportjs-desktop')
.removeClass('viewportjs-desktop-wide')
.removeClass('viewportjs-tablet')
.removeClass('viewportjs-tablet-wide')
.removeClass('viewportjs-mobile');
if (bodyWidth >= 1028) {
bodyElement.addClass('viewportjs-desktop');
if (bodyWidth >= 1120) {
bodyElement.addClass('viewportjs-desktop-wide');
}
}
else if (bodyWidth >= 640) {
bodyElement.addClass('viewportjs-tablet');
if (bodyWidth >= 728) {
bodyElement.addClass('viewportjs-tablet-wide');
}
}
else {
bodyElement.addClass('viewportjs-mobile');
}
};
try {
checkViewportJS();
$(window).resize(checkViewportJS);
}
catch (e) { console.log('error @ checkViewportJS', e); }
};
$(document).ready(initViewportJs);
})(jQuery || false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment