29
Apr '12

Automatic Font Resizing with jQuery Mobile

In the process of learning mobile application design with jQuery Mobile I struggled greatly with making my layouts work with different screen sizes. There are a hundred and one articles online about screen sizes, resolutions etc but no clear consensus on an easy way to make your applications scale from phone to tablet. So I thought I’d build a plugin to do just that.
The idea behind this is simply that you design you application on a certain device with a certain screen width and make sure all your fonts are in the correct proportion. If you set a base font size and then use em sizes on all the rest then it’s simply a case of using a little logic on the current screen width to calculate what that base font size should be in order keep your scale correct.

(function($) {
	$.fn.dynamicText = function(options) {
		options = jQuery.extend({
			maxFontSize: 14,
			minFontSize: 6,
			baseFontSize: 10,
			baseScreenWidth: 800
		}, options);

		var element = $(this);

		doTextResize();

		$(window).resize(function() {
			doTextResize();
		});

		function doTextResize() {
			var font_size = parseInt(options.baseFontSize * $(window).width() / options.baseScreenWidth);

			font_size = (font_size = options.minFontSize) ? font_size : options.minFontSize;
			element.css('font-size', font_size + 'pt');
		}
	}
})(jQuery);

Options

  • maxfontSize – maximum size it will adjust your base font to
  • minFontSize – minimum size it will adjust your base font to
  • baseFontSize – the base font size you used for your development
  • baseScreenWidth – the screen width you used for your development

Calling the Function

$('body').dynamicText({ baseFontSize: 14 });
$('.container').dynamicText({ maxFontSize: 8, minFontSize: 16 });

You’ll notice that, although you will generally want to call this function on the entire body of your page, you by no means have to. It will set the base font of any specified element and as such scale all those below it.

The window resize listener is not strictly necessary for a static page but it will trigger when you change the orientation of your device which could be useful.

Leave a Reply