user1072337
user1072337

Reputation: 12945

Text shortening method in jquery not shortening div text

I am pulling some text from a database, and I would like the div it appears in to shorten it to a certain character amount. I am using this:

Script:

$(".activity_body").text($(this).text().substr(0, 120)+'...');

HTML:

<div class="activity_body">{{$fanartist->description}} <a href="/artists/{{$fanartist->id}}">See more...</a></div>

This isn't shortening the text like it should. Do you know what may be going wrong here? Thank you.

This div class appears many times (dynamic rendering), does this have anything to do with it? Thank you.

Upvotes: 0

Views: 79

Answers (2)

kalley
kalley

Reputation: 18462

Your this is not referring to $(".activity_body"). You need do one or the other of the following:

var activityBody = $(".activity_body");
activityBody.text(activityBody.text().substr(0, 120)+'...');
// or
$(".activity_body").each(function() {
    $(this).text($(this).text().substr(0, 120)+'...');
});

Here's a fiddle where it is working: http://jsfiddle.net/FSxj5/

Upvotes: 1

Harish Ambady
Harish Ambady

Reputation: 13121

If you are using php then you can shorten the string from server itself using php substr function like:

substr ( $string , $start ,$length )

which returns the portion of string specified by the start and length parameters.

See the function in php.net

Upvotes: 0

Related Questions