fefe
fefe

Reputation: 9055

limit text with jquery

I'm trying to limit my descriptions texts in a list view to an amount number of charachters with the option to toggle down the rest of it on click. Limiting the text is not a problem it works with the following code snippet http://jsfiddle.net/lgtsfiddler/G42dR/5/

$("p").each(function(i) {
    len = $(this).text().length;
    if (len > 150) {
        $(this).text($(this).html().substr(0, 150));
    }
});

How could add the dropdown event to it?

Upvotes: 0

Views: 1277

Answers (2)

user1726343
user1726343

Reputation:

One way of doing this would be to wrap the "preview" portion and the remaining portion of your text in separate spans. Then, you could add a link that toggles whether the span containing the remaining portion of the text is hidden or displayed:

$(this).html("<span>" + $(this).text().substr(0,150) + "</span><span style='display:none'>" + $(this).text().substr(150) + "</span>");

var link = $("<a href='#' class='more'>More..</a>");
$(this).append(link);
$(link).click(function(){
    $(this).prev().toggle();
    $(this).html($(this).html()=="More.."?"Less":"More..");
});

Demo: http://jsfiddle.net/G42dR/9/

Upvotes: 2

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

Does this help you:

            $('p').each(function(){
                if($(this).text().length > 150){
                    $(this).attr('data-text', $(this).text());
                    $(this).text($(this).text().substring(0, 150));
                    $(this).after($('<a onclick="$(this).prev().text($(this).prev().attr(\'data-text\')); $(this).remove();"> Read more...</a>'));
                }
            });

Upvotes: 1

Related Questions