Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Plugin "readmore", trim text without cutting words

I'm using http://rockycode.com/blog/jquery-plugin-readmore/ for trim long text and add a "See more" link to reveal all the text.

I would love to avoid cutting words, how could I do that?

If the limit is 35, don't cut the w...

but

If the limit is 35, don't cut the word... (and in this case, trim it at 38 and then show the hidden text from 39th chtill the end.

like image 616
Santiago Avatar asked Dec 21 '22 14:12

Santiago


2 Answers

Instead of doing this:

$elem.readmore({
  substr_len: 35
});

You could do this

$elem.readmore({
  substr_len: $elem.text().substr(0, 35).lastIndexOf(" ")
});

What we're doing is to go to the latest space posible before index 35. Of course 35 can be variable. Also you could put it into a function to reuse it.

Hope this helps

like image 160
Edgar Villegas Alvarado Avatar answered Jan 07 '23 01:01

Edgar Villegas Alvarado


You can change the abridge function within that plugin as follows:

function abridge(elem) {
  var opts = elem.data("opts");
  var txt = elem.html();
  var len = opts.substr_len;
  var dots = "<span>" + opts.ellipses + "</span>";
  var charAtLen = txt.substr(len, 1);
  while (len < txt.length && !/\s/.test(charAtLen)) {
      len++;
      charAtLen = txt.substr(len, 1);
  }
  var shown = txt.substring(0, len) + dots;
  var hidden = '<span class="hidden" style="display:none;">' + txt.substring(len, txt.length) + '</span>';
  elem.html(shown + hidden);
}

...and it will behave as you desire. You might want to add an option to turn this feature off and on, but I'll leave that up to you.

See working example →

like image 36
mVChr Avatar answered Jan 07 '23 01:01

mVChr