0
votes

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');
        }
    });
});
4
why do you have if condition if you do nothing .. put else condition directly. - Bhushan Kawadkar
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
.autotitle refers to a class. I changed it into this. Now it changes every .autotitle class div without counting characters - Juárez
codejQuery(function ($) { $(window).load(function() { var textLength = $(".autotitle").val().length; if(textLength < 20) { $(".autotitle").css('font-size', '12px'); } }); }); code - Juárez
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

4 Answers

4
votes

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');
        }
});
0
votes

try this,Demo use html instead of using val

       var textLength = $('.autotitle').html().length;
0
votes

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.

0
votes

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');