Posted By

praveensewak on 06/01/12


Tagged

jquery paragraph shorten


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

BrockSamsom


jQuery Shorten paragraphs


 / Published in: jQuery
 

jQuery shorten content inside container.

  1. /*
  2. Author: Praveen Sewak
  3. Date: 01/06/2012
  4. URL: http://www.praveensewak.com/
  5. Credits: Based on jQuery Shorten lib by Viral Patel: http://bit.ly/fBrElf (Thanks dude!).
  6. I just added functionality so that it shows/hides elements inside a container ('div > p')
  7. */
  8.  
  9. (function($){
  10. $.fn.shorten = function (settings) {
  11. var config = {
  12. item: "p",
  13. showItems: 2,
  14. moreText: "more",
  15. moreClass: "morelink",
  16. lessText: "less",
  17. toggleSpeed: "fast"
  18. };
  19.  
  20. if(settings){
  21. $.extend(config, settings);
  22. }
  23.  
  24. $('.morelink').live('click', function(){
  25. var $this = $(this);
  26. if($this.hasClass('less')){
  27. $this.removeClass('less');
  28. $this.html(config.moreText);
  29. }else{
  30. $this.addClass('less');
  31. $this.html(config.lessText);
  32. }
  33. $('.shorten_extra', $this.parent()).slideToggle(config.toggleSpeed, 'linear');
  34. return false;
  35. });
  36.  
  37. return this.each(function(){
  38. var $this = $(this);
  39. var content = $this.html();
  40. var count = $(config.item, $this).size();
  41.  
  42. if(count > config.showItems){
  43. var pre = '';
  44. for(i=0;i<config.showItems;i++){
  45. pre += $(config.item + ':eq(' + i + ')', $this)[0].outerHTML;
  46. }
  47. var extra = '';
  48. for(i=config.showItems;i<count;i++){
  49. extra += $(config.item + ':eq(' + i + ')', $this)[0].outerHTML;
  50. }
  51. }
  52. var html = '<span class="shorten_original">' + pre + '</span><span class="shorten_extra">' + extra + '</span><a href="javascript://nop/" class="' + config.moreClass + '">' + config.moreText + '</a>';
  53. $this.html(html);
  54. $('.shorten_extra').hide();
  55. });
  56. };
  57. })(jQuery);

Report this snippet  

You need to login to post a comment.