anavdesign
4/22/2016 - 3:39 AM

JS: Viewport Width

JS: Viewport Width

/*
 =====================================================================
  $Viewport Width
 =====================================================================
 *
 * Usage
 * $('body').viewportWidth();
 */

(function($) {
    $.fn.viewportWidth = function(options) {

	// Options
	var settings = $.extend({
		xs: '480', 	// XSmall
		sm: '600', 	// Small
		md: '768', 	// Medium
		lg: '1000', // Large
		xl: '1200' 	// XLarge
		}, options );

		var $elm =$('<div id=js-viewport-width />');

		$elm
			.appendTo('body')
			.css({
				'position': 'fixed',
				'bottom': '0',
				'left': '0',
				'right': '0',
				'padding': '10px',
				'backgroundColor': 'black',
				'color': 'white',
			})
			.html('Width: <span class=js-width />px ' +
				'&emsp;&emsp;' +
				'Size: <span class=js-size>XXSmall</span>');

		// Viewport Size
		function viewportSize() {
			$elm.children('.js-width').html($(window).width());
		}

		// Breakpoint
		function breakpoint(){
			if ($(window).width() >= settings.xl) {
				$elm.children('.js-size').html('XLarge');
			} else if ($(window).width() >= settings.lg) {
				$elm.children('.js-size').html('Large');
			} else if ($(window).width() >= settings.md) {
				$elm.children('.js-size').html('Medium');
			} else if ($(window).width() >= settings.sm) {
				$elm.children('.js-size').html('Small');
			} else if ($(window).width() >= settings.xs) {
				$elm.children('.js-size').html('XSmall');
			}
		}

		// Display window width at page load
		viewportSize();
		breakpoint();

		// Update window width on resize
		$(window).resize(function() {
			viewportSize();
			breakpoint();
		});
	};
})(jQuery);