0

I'm trying to adjust title sizes depending on character length. (wordpress)

This is what I have so far. It doesn't return any error but it doesn't work.

jQuery(function ($) {
    $(window).load(function () {
        var textLength = $('.autotitle').val().length;
        if (textLength < 20) {
            // Do noting 
        } else if (textLength > 20) {
            $('.autotitle').css('font-size', '16px');
        }
    });
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
Juárez
  • 121
  • 1
  • 1
  • 10
  • why do you have if condition if you do nothing .. put else condition directly. – Bhushan Kawadkar Jul 14 '14 at 12:38
  • 1
    What kind of html element is `.autotitle` ? If it's not `input` try `.html()` instead of `.val()` but note that it may include inner tags and whitespaces. – Viktor Bahtev Jul 14 '14 at 12:39
  • .autotitle refers to a class. I changed it into this. Now it changes every .autotitle class div without counting characters – Juárez Jul 14 '14 at 12:51
  • `code`jQuery(function ($) { $(window).load(function() { var textLength = $(".autotitle").val().length; if(textLength < 20) { $(".autotitle").css('font-size', '12px'); } }); }); `code` – Juárez Jul 14 '14 at 12:51
  • actually, it counts and works, but it applies css to all the elements with that class. How can I apply it only to the ones that fit into the count? – Juárez Jul 14 '14 at 12:55

4 Answers4

4

Many times one would like to decrease font size (make it smaller) when text is long based on letter count (text might have been entered through some CMS or translated text)

http://jsfiddle.net/jfbrLjt2/

 $('.text').each(function(){
     var el= $(this);
       var textLength = el.html().length;
        if (textLength > 20) {
            el.css('font-size', '0.8em');
        }
});
Yaron Bit
  • 56
  • 4
0

try this,Demo use html instead of using val

       var textLength = $('.autotitle').html().length;
hari
  • 1,874
  • 1
  • 16
  • 10
0

solved it with a php function

function trim_title() {
$title = get_the_title();
$limit = "14";

if(strlen($title) <= $limit) {
echo $title;
} else {
echo '<span class="longtitle">'; echo $title; echo '</span>';
}
}

thanks to everyone.

Juárez
  • 121
  • 1
  • 1
  • 10
0

If u use .autotitle then changes will be applied to every element where u use .autotitle as class attribute ...

Instead that u can use id attribute of particular element to apply changes to only that element

Ex :

$('#id').css('font-size','16px');