JCHASE11
JCHASE11

Reputation: 3941

Creating a Conditional Statement that Applies Rules Based on the Number of Characters

I am stuck in a situation where I have a container with a single line of text, perfectly centered. Occasionally, the text is longer, and it breaks onto a second line. This throws off the layout, so I need a solution. I am thinking of using jquery to say, "if the number of characters goes above 28 characters, then apply a margin-top of -10px to center the text."

How would you go about this in jquery? That is, creating a conditional statement that applies rules based on the number of characters? Here is my html, the span class of redstrip needs a margin-top of -10 if the number of characters goes above 28 characters:

<a href="#">
    <img src="images/dummy3.jpg" alt="dummy">
    <span class="redStrip">Here is a bunch of dummy text that is a bit too long</span>
</a>

Upvotes: 0

Views: 179

Answers (2)

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14737

While Anthony's answer is spot on, it'll only work for singular elements because of the behavior of .text() on jQuery wrapped sets with multiple elements. (i.e. if .redstrip selected more than one DOM element, a simple if wouldn't cut it).

Expanding on his answer, you may want to apply a callback filter, or an .each().

// via filter
var redStrip = $('.redStrip');
redStrip
    .filter(function () { return $(this).text().length > 28 })
    .css('margin-top','-10px')
    ;

// via .each()
var redStrip = $('.redStrip');
redStrip.each(function () {
    var $t = $(this);
    if ($t.text().length > 28) {
        $t.css('margin-top','-10px');
    }
});

Upvotes: 2

Anthony Grist
Anthony Grist

Reputation: 38345

Is the content constant once the page has loaded, or is it updated by user interaction with the page? Assuming the former, you can just do this:

var redStrip = $('.redStrip');
if(redStrip.text().length > 28) {
    redStrip.css('margin-top', '-10px');
}

If you're dynamically updating the content of redStrip, you could always wrap the above code in a function and also call that every time you do.

EDIT: Make that '-10px' in the .css() call.

Upvotes: 1

Related Questions