Patrick Estabrook
Patrick Estabrook

Reputation: 125

Trying to shorten a body of text that may have links in it

I'm trying to figure out a way to shorten a body of text that may contain links.

<div class="bio">
    Banjo my soundcloud is <a href="http://soundcloud.com/username">http://soundcloud.com/username</a>
    Echo Park kale chips blog, cred pitchfork keffiyeh mixtape tumblr photo booth artisan helvetica
    meggings fashion axe roof party. Aesthetic biodiesel direct trade butcher, iPhone occupy before
    they sold out trust fund mumblecore cornhole food truck DIY narwhal freegan. Salvia try-hard
    freegan, Brooklyn Marfa craft beer fanny pack dreamcatcher High Life irony sriracha. Mumblecore
    Terry Richardson ethnic, pop-up tattooed sartorial 3 wolf moon banjo biodiesel church-key semiotics
    polaroid Etsy Schlitz hashtag. Wes Anderson gluten-free lomo brunch, raw denim plaid Schlitz salvia. 
</div>

I tried initially to shorten the body of text by having a cutoff number of characters after which I would insert a 'more' link, put the rest of the text in a span, and hide the span until the 'more' link was clicked. However, if a user decides to put a link in the wrong place, inserting the 'more' link clobbers the anchor tags that the user put in.

This is the kind of solution I've found for this problem that doesn't work: http://www.bookofzeus.com/articles/dynamically-shortened-text-using-jquery/

What's a good way to shorten a body of text that may have anchor tags in it?

Upvotes: 1

Views: 93

Answers (2)

Ronnie
Ronnie

Reputation: 11198

You're right, that jquery demo code didn't work, but the demo did. I had to fix some things, but here is a fiddle you can peak at. I used your textual info too.

http://jsfiddle.net/Fyzxn/1/

$(document).ready(function() {
    var orgContent = $('.bio').html();
    var txtContent = $('.bio').text().substr(0, 50) + '... <a id="morelink">more</a>';
    $('.bio').html(txtContent);
    $("body").on("click", '#morelink', function(){
        $('.bio').html(orgContent);
        $('<a id="lesslink"> less</a>').appendTo('.bio');
    });
    $("body").on("click", '#lesslink', function(){
        $('.bio').html(txtContent);
    });
});

Upvotes: 3

Filippos Karapetis
Filippos Karapetis

Reputation: 4652

The easiest way I can think of is to dynamically create a plain text version of the text body, which will be what will be shown as a preview. That way, you won't have issues cutting off any markup, as you'll only be processing plain text.

jQuery's text() method can be used to remove all HTML tags from a string. This way, you can create a text-only preview, and show the actual content together with the HTML tags when the user clicks on the "more" link

Upvotes: 2

Related Questions