doubleplusgood
doubleplusgood

Reputation: 2556

Creating Excerpt text with a read more link

I have a varchar field full of text and I want to be able to just show a 100 character snippet of the text, and show a "Read More..." link at the end of the snippet. When the user clicks "Read More..." I would like the page to expand and display the rest of the text.

I guess the 'show/hide' featured could be done with jQuery but i wasn't sure if ASP had some function to effectively split the varchar field of text in two?

My content is currently being pulled into the page using;

<%=StripHTML(rspropertyresults.Fields.Item("ContentDetails").Value)%>

Which uses this function to strip out any HTML tags;

<%
Function stripHTML(strHTML)
  ''Strips the HTML tags from strHTML

  Dim objRegExp, strOutput
  Set objRegExp = New Regexp

  objRegExp.IgnoreCase = True
  objRegExp.Global = True
  objRegExp.Pattern = "<(.|\n)+?>"

  ''Replace all HTML tag matches with the empty string
  strOutput = objRegExp.Replace(strHTML, "")

  ''Replace all < and > with &lt; and &gt;
  strOutput = Replace(strOutput, "<", "&lt;")
  strOutput = Replace(strOutput, ">", "&gt;")

  stripHTML = strOutput    ''Return the value of strOutput

  Set objRegExp = Nothing
End Function
%>

Upvotes: 2

Views: 10989

Answers (3)

RB.
RB.

Reputation: 37222

Expanding on Phil Wheeler's sample, here is an example which shows applying this to every td element in a table, using jQuery's Each function.

<html>
<head>
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js" 
            type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("td").each(
                function( intIndex ) {
                    var textToHide = $(this).text().substring(100);
                    var visibleText = $(this).text().substring(1, 100);

                    $(this)
                        .html(visibleText + ('<span>' + textToHide + '</span>'))
                        .append('<a id="read-more" title="Read More" style="display: block; cursor: pointer;">Read More&hellip;</a>')
                        .click(function() {
                            $(this).find('span').toggle();
                            $(this).find('a:last').toggle();
                        });

                    $(this).find("span").hide();
                }
            )

        });
    </script>
</head>
<body>
    <table border="1">
        <tr>
            <td>
                "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
            </td>
            <td>
                "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
            </td>
        </tr>
    </table>
</body>

Upvotes: 2

Pete Duncanson
Pete Duncanson

Reputation: 3256

Everything you are after is doable and quite easy really once you get your head around it. I'm not a jquery man (Mootools for me!) so can't help you there.

For the ASP truncate function though you need to be careful. You have the right idea though in stripping the html or else you could leave an un-closed tag open (an unclosed div or script tag could really mess with your layout).

I would:

  • Strip it first
  • If the length was less than you wanted to truncate it by just display it
  • Other wise use Left( your_string, 300 ) to only grab the first 300 characters (for instance) then append a "..." on the end or what ever. Nice and easy.

You can try to get fancy and try to split it on the next space so you don't cleave words in half but can't remember off hte top of my head how to do that in VBScript. JS no problem!

Upvotes: 0

Phil.Wheeler
Phil.Wheeler

Reputation: 16858

Try using this as a starting point.

<p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas massa lectus, pulvinar vel scelerisque eget, 
    rutrum et nisi. Mauris semper viverra lorem sit amet faucibus. Fusce egestas metus sit amet lectus interdum 
    sollicitudin. Maecenas accumsan metus scelerisque tortor lobortis et pretium nibh cursus.
</p>
<script type="text/javascript">
    $(function() {
        var textToHide = $('p').text().substring(100);
        var visibleText = $('p').text().substring(1, 100);

        $('p')
            .html(visibleText + ('<span>' + textToHide + '</span>'))
            .append('<a id="read-more" title="Read More" style="display: block; cursor: pointer;">Read More&hellip;</a>')
            .click(function() {
                $(this).find('span').toggle();
                $(this).find('a:last').hide();
            });

        $('p span').hide();
    });
</script>

So what I've done here is create two variables: one to hold the first 100 characters ("visibleText") and one to hold the rest ("textToHide").

We then tell jQuery to find every paragraph tag (you'll likely want to define a more specific selector), wrap the text in a span tag and put that all back on the visible text, append a link at the end of all this to show the text we'll be hiding and finally assign a click event to do it.

The click function simply looks for all span tags in the paragraph, toggles them visible (the show() function might be a better choice here, actually) and then hides the "Read more" link.

Finally we make sure our paragraph's span tags start off being hidden. You might actually want to create a CSS rule (p span {display: none;}) so that the text still starts hidden, but is done faster than JavaScript. A jQuery show() function will still override that css rule when called.

That should about do it.

Upvotes: 13

Related Questions