Results 1 to 2 of 2

Thread: dynamically changing font with text size

  1. #1
    Join Date
    Aug 2009
    Posts
    74
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default dynamically changing font with text size

    hi

    i got one doubt if we can change font size of a text dynamically

    ex: if we give name as SACHIN TENDULKAR it should be shown as font size of some 40 or 60

    and if we give another text as TENDULKAR TON HELPS INDIA TO WIN THE MATCH this should be automatically adjusted to font size of some 30 to 35.

    I searched Google but i didn't find it if anyone one know plz help me out

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    40 or 60 what? 30 to 45 what? Anyways, font sizes should be set as % via css style. You would probably also want a minimum and maximum size. Here's one approach:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <style type="text/css">
    .sizer {
     font-family: sans-serif;
    }
    </style>
    <script type="text/javascript">
    function sizeText(){
    	for(var i = 0, spans = document.getElementsByTagName('span'); i < spans.length; ++i){
    		if(spans[i].className === 'sizer'){
    			spans[i].style.fontSize = Math.max(Math.min((100 / spans[i].firstChild.nodeValue.length) * 48, 300), 120) + '%';
    		}
    	}
    }
    </script>
    </head>
    <body>
    <span class="sizer">SACHIN TENDULKAR</span><br>
    <span class="sizer">TENDULKAR TON HELPS INDIA TO WIN THE MATCH</span>
    <script type="text/javascript">
    sizeText();
    </script><br>
    </body>
    </html>
    Let's zoom in on the highlighted line:

    Code:
    spans[i].style.fontSize = Math.max(Math.min((100 / spans[i].firstChild.nodeValue.length) * 48, 300), 120) + '%';
    Code:
    48, 300), 120
    The 48 is the multiplier, the larger this is, the larger everything affected by this script will tend to be, if you increase or decrease it too much, you wont see much difference between the smaller and larger sizes. 300 is the maximum % size, and 120 is the minimum % size. The minimum should be at least 90 though, otherwise it will could get pretty tiny.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •