Mootools auto font size adjustment

5 February 2009| No Comment| Print

font-size-mootools

After browsing the vast space that is the internet, i stumbled upon a great piece of code that, depending on the number of words in a div automatically adjusts the font size. This could be really useful if you have a list of user feedback, that you want to jazz up.

So whats the code doing? Simply put. The code looks for the text within class ‘.text’ then counts the number of words by exploding the text where there is a space, then its just a matter of putting in some if statements to adjust the font size using ‘el.setStyle’.

The Code:

window.addEvent('domready',function() {

    	$quote = $$('.text p:first-child');

        $each($quote,function(el) {

            var $numWords = el.get('text').split(' ').length;

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

            });

    	});

make sure that you include the mootools core js file.

The HTML:

<div class="text">

Don't expect me to write anything interesting in here as this is really just a test! but you can check out the demo over at papermashup.com</div>

demo

Credit to Chris Coyier over at CSS tricks for this one.


Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.

Your Ad Here