Set font size based on Word Count jQuery

I have several articles, but all of them should correspond to the same space. Characters are limited to 140. What I want to do is change the font size based on the characters in my paragraph. Therefore, if there are fewer characters in the paragraph, I would like the font size to become larger and vice versa.

My code below does not seem to work and was wondering if anyone could help me?

What is happening at the moment, it seems that it takes the last place, because the font size of all paragraphs is 8em :(

I really appreciate any help and thanks in advance!

Here is the code:

$(function(){ var $quote = $(".question p"); var $numWords = $quote.text().split("").length; if (($numWords >= 1) && ($numWords < 20)) { $quote.css("font-size", "2.2em"); } else if (($numWords >= 20) && ($numWords < 60)) { $quote.css("font-size", "1.8em"); } else if (($numWords >= 60) && ($numWords < 100)) { $quote.css("font-size", "1.2em"); } else if (($numWords >= 100) && ($numWords < 140)) { $quote.css("font-size", "0.9em"); } else { $quote.css("font-size", "0.8em"); } }); 
+4
source share
2 answers

Your problem is that you do not consider each paragraph separately: see http://jsfiddle.net/wkEMK/1/

 $(function(){ $(".question p").each(function () { var numChars = $(this).text().length; if ((numChars >= 1) && (numChars < 20)) { $(this).css("font-size", "2.2em"); } else if ((numChars >= 20) && (numChars < 60)) { $(this).css("font-size", "1.8em"); } else if ((numChars >= 60) && (numChars < 100)) { $(this).css("font-size", "1.2em"); } else if ((numChars >= 100) && (numChars < 140)) { $(this).css("font-size", "0.9em"); } else { $(this).css("font-size", "0.8em"); } }); }); 

The source code produced the number of characters for ALL paragraphs that matched the query ".question p". for example, if you have two paragraphs, one with ten characters, the other with twenty characters, your JS will run once, thirty in all, and not process each paragraph in turn.

+4
source

Do it this way using . css . Thus, it will change each font size p of the elements according to the number of characters inside each element p

 $(function(){ $(".question p").css('font-size',function(){ var $numWords = $(this).text().length; // get length of text for current p element if (($numWords >= 1) && ($numWords < 20)) { return "2.2em"; } else if (($numWords >= 20) && ($numWords < 60)) { return "1.8em"; } else if (($numWords >= 60) && ($numWords < 100)) { return "1.2em"; } else if (($numWords >= 100) && ($numWords < 140)) { return "0.9em"; } else { return "0.8em"; } }); }); 

Fiddle

+3
source

All Articles