
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; ($numWords < 10)) {
el.setStyle('font-size','36px');
}
else if (($numWords >= 10) &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; ($numWords < 30)) {
el.setStyle('font-size','28px');
}
else if (($numWords >= 30) &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>
Credit to Chris Coyier over at CSS tricks for this one.
Not really a comment but a question: I have a client who personalizes dinnerware with names or photos. We have encountered an issue with the names. We would like to be able to populate the text area to automatically size and center. Is that possible? The original files are done in PhotoShop.
Designer and web developer, Co-founder and Technical Director at Harkable.com London. Previously I worked at InMobi, Spotify and MySpace. Interests include photography and making short videos. Also an avid F1 fan.
Follow us on Twitter and get in-stream updates.
Subscribe to all the Papermashup tutorials and articles straight to your RSS reader.
Sign up and get all the Papermashup tutorials straight to your inbox.
One Response about Mootools auto font size adjustment