Sunday, February 17, 2013

How to increase/decrease font size to occupy complete width


<SCRIPT type=text/javascript>
        String.prototype.GetNumericFontValue = function () {
            return Number(this.replace('px', '').replace('pt', '').replace(/\s/g, ''));// removing px, pt, any type used in css and spaces
        };
        $(document).ready(function () {
            var standardTextWidth = 470;
            standardTextWidth = standardTextWidth - 20; /*we are taking 20 px less accuracy due different width of chars like i, W, l , M,j, etc*/
            var isExcecuted = false;
            $('.textContainer').each(function (index) {
                isExcecuted = false;
                var currentFontSize = String($(this).css('font-size')).GetNumericFontValue();
                /*Increase the font size to occupy available width*/
                for (currentFontSize; $(this).width() < standardTextWidth; currentFontSize = currentFontSize + 1) {
                    $(this).css('font-size', currentFontSize + 'px');
                    isExcecuted = true;
                }
                /*Decrease the font size to occupy available width*/
                if (!isExcecuted) {
                    for (currentFontSize; $(this).width() > standardTextWidth; currentFontSize = currentFontSize - 1) {
                        $(this).css('font-size', currentFontSize + 'px');
                    }
                }
            });

        });
        /*
        How to use:
        Need to change the selecter " $('.textContainer')" as per DOM and standardTextWidth default width of title.

        Limitation of above function:
        1. Width will increase or decrease in proportions of characters in string.
        2. Width of each char is different.
        */
    </SCRIPT>

No comments: