jQuery: create a font resizer

jQuery: create a font resizer

How to increase or decrease the font size of an element with jQuery.

Letting users select their preferred font size when viewing your pages is always a good practice, especially when users have a little knowledge of how their browser settings work. jQuery offers a simple and effective way to accomplish this task.

We can define a small plugin which accepts two options, namely the references to the buttons used to increase or decrease the base font size of the element:


(function($) {
    $.fn.fontResize = function(options) {
        var settings = {
            increaseBtn: $('#increase-font'),
            decreaseBtn: $('#decrease-font')
        };
        options = $.extend(settings, options);

        return this.each(function() {
            var element = $(this);


            options.increaseBtn.on('click', function(e) {
                e.preventDefault();
                var baseFontSize = parseInt(element.css('font-size'));
                element.css('font-size', (baseFontSize + 1) + 'px');

            });

            options.decreaseBtn.on('click', function(e) {
                e.preventDefault();
                var baseFontSize = parseInt(element.css('font-size'));
                element.css('font-size', (baseFontSize - 1) + 'px');

            });

        });

    };


})(jQuery);

The font-size property is always computed in pixels with the form numberpx. For that reason we first need to extract the numeric portion of each value with the aid of the parseInt() function. Done that, we can add or subtract 1 to / from the current value. An example:


$(function() {
    $('#content').fontResize();

});​

[view-example url="http://jsfiddle.net/gabrieleromanato/XB3m7/"]