Bootstrap viewport class on resize

When using Bootstrap you might want some page elements to react on the viewport. The best method will still be using the fluid grid system, so try to setup your page using the grid system. But in some cases you want to use a CSS class and/or Javascript to tweak your layout.

The setup will use Responsive Bootstrap Toolkit and it will add the grid viewport-class to the HTML DOM element. This can be usefull if you want to add some viewport-specific stylesheets (Pro tip: use SASS to generate your CSS code).

First start including the vendors:

<script src="js/jquery.min.js?v=1.11.3"></script>
<script src="js/bootstrap.min.js?v=3.3.5"></script>
<script src="js/bootstrap-toolkit.min.js?v=2.5.0"></script>

Now create your own javascript.js file and include it after the vendors listed above. Paste the following code in your Javascript file:

(function($, document, window, viewport){
	var htmlObj = $("html"), viewportClass = "", 
	setViewportClass = function(){
		htmlObj.removeClass(viewportClass);
		viewportClass = "is-screen-" + viewport.current();
		htmlObj.addClass(viewportClass);
	};
	$(document).ready(function() {
		setViewportClass();
	});
	$(window).resize(
		viewport.changed(function(){
			setViewportClass();
		})
	);
})(jQuery, document, window, ResponsiveBootstrapToolkit);

Now use the DOM inspector to see the HTML element class attribute reacting on your viewport (resize/rotate your screen to see it in action).

Leave a Reply

Your email address will not be published. Required fields are marked *