Use jQuery to count letters and apply a .class if a set number is reached.

January 1, 2013 : Posted in: ,

jQuery Count Text post image

This came in handy when working with a limited heading space for a site’s H1. After 45 letters the title was extending behind other layout elements. To solve this I added a jQuery snippet to count the title letters and apply a class to them after 45 letters. With the class I was able to use CSS to shrink the font size and re-position the H1 to play nicely in its space.

Javascript

$(document).ready(function(){
    $(".h1-container h1").filter(function(){
        return $(this).text().length >=45;
    }).addClass('titleLong');
});

CSS

h1.titleLong{
    margin-top:10px;
    font-size:17px;
    width:75%;
    line-height:22px;
}