Colin Shaw
Colin Shaw

Reputation: 56

Smaller font-size if the string length of the div is greater than 10

I have a div that I want to detect the length of; if it's 10 or more, I want it to display in a smaller font-size.

$(window).load(function() {
  function adjustFontSize() {
    var theTitleLength = $('.article-title-on-list').text.length;
    if (theTitleLength >= 10) {
      $('.article-title-on-list').css('font-size', '1.5rem');
    } else {
      $('.article-title-on-list').css('font-size', '2rem');
    };
  };
  adjustFontSize();
};
<div class="article-title-on-list">12345678901234567890</div>

The function fails silently.

Upvotes: 1

Views: 81

Answers (2)

Colin Shaw
Colin Shaw

Reputation: 56

I've updated my code with an .each() function. In case someone want to use this:

$('.article-title-on-list').each(function() {
  var theTitleLength = $(this).text().length;
  console.log(theTitleLength);
  if (theTitleLength >= 14) {
    $(this).css('font-size', '1.7rem');
  } else {
    $(this).css('font-size', '2rem');
  };
});
<div class="article-title-on-list">12345678901234567890</div>
<div class="article-title-on-list">123456789012345678901234567890</div>
<div class="article-title-on-list">1234567890</div>

Thanks again for Nathan's help.

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

text is method and not property. use .text() instead of .text

 var theTitleLength = $('.article-title-on-list').text().length;

Upvotes: 1

Related Questions