Dynamically shortened Text using jQuery

Posted on Saturday March 23, 2013 / by Eric Potvin

You ever read long, almost never ending paragraphs without thinking seriously, this should be shorter or I should be able to shrink this!?

For those who thinks this or saying: I can do this?, there's a very simple solution for this using jQuery.

The HTML

Let start with a simple text (lorem ipsum) that look like this:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet, nunc eget laoreet sagittis,<p/p>
<p>quam ligula sodales orci, congue imperdiet eros tortor ac lectus. Duis eget nisl orci. Aliquam mattis purus non mauris blandit id luctus felis convallis.</p>
<p>Integer varius egestas vestibulum. Nullam a dolor arcu, ac tempor elit. Donec.<p/p>

CSS

Let create a basic style, sorry I won't do this for you.

* {
  margin: 0px;
  padding: 0px;
}
a {
  color: blue;
  cursor: pointer;
}
p {
  margin: 1em 0;
}

jQuery Code

Now, the fun part. This will take the text and turn it into: Lorem ipsum dolor ... more. The "more" will be clickable and the text will automatically expand. In this case, I use only the first 20 characters: $('#more').text().substr(0, 20), if you need more, simply change the number from 20 to the one you like.

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