Sheshadrinath R
Sheshadrinath R

Reputation: 99

Dynamically change the font size by jQuery

I have data coming in JSON format and I need to render the data on the Web browser. There will be many div containers where I need to render the text also. All the div containers may be of different dimensions. The text that goes inside this div container will also be dynamic. I need to set the font size in such a way that, the text should be big enough occupying as much as possible space inside the div container and also text should not be clipped.

The challenge here is the text length. If it is a bigger text, then the font size should automatically reduce so that it will still fit inside the div container without data being clipped.

Please let me know if there is any way of achieving this.

Upvotes: 2

Views: 5004

Answers (2)

Nathaniel Flick
Nathaniel Flick

Reputation: 2963

CSS Tricks to the rescue again: http://css-tricks.com/set-font-size-based-on-word-count/

Per that link you can detect/set word limits and then add an inline font size declaration to suit:

$(function(){

var $quote = $(".post p:first");

var $numWords = $quote.text().split(" ").length;

if (($numWords >= 1) && ($numWords < 10)) {
    $quote.css("font-size", "36px");
}
else if (($numWords >= 10) && ($numWords < 20)) {
    $quote.css("font-size", "32px");
}
else if (($numWords >= 20) && ($numWords < 30)) {
    $quote.css("font-size", "28px");
}
else if (($numWords >= 30) && ($numWords < 40)) {
    $quote.css("font-size", "24px");
}
else {
    $quote.css("font-size", "20px");
}    

});

Upvotes: 3

Aminul
Aminul

Reputation: 1738

You can use jQuery TextFill

This jQuery plugin resizes text to make it fit into a container. The font size gets as big as possible

Usage From Official site:

Remember to include jQuery and jQuery TextFill:

<script src="jquery.min.js"></script>
<script src="jquery.textfill.min.js"></script>

Select which element you'll use. Make sure to: Specify the parent's width and height. Put the text inside of a child by default (see Options to change this)

<div id='my-element' style='width:100px;height:50px;'>
  <span>The quick brown fox jumps over the lazy dog</span>
</div>

Initialize jQuery TextFill

 <script>
$(function() {
    $('#my-element').textfill({

    });
});
</script>

Fiddle Demo

Upvotes: 1

Related Questions