Ellipsis on list item body using jQuery


A common question to receive is on list items with a long body (eg. Announcements) and then show only X characters and optionally a ‘read more’ link. Many ways to solve this but I went for the following: a Custom Field Type that renders the short text with ellipsis using jQuery.

This is another example using the Advanced Computed Field in a creative way. The ACF allows you to create computed fields referencing other fields or data in your list and manipulating them through CAML or JavaScript. It has the advantage that this can be done from within the browser, however I admit CAML isn’t the easiest of things to comprehend in the SharePoint technology stack.

Ellipsis sample

This ellipsis displays the first 20 characters of the plain text version of the Announcement Body

<FieldRefs> 
     <FieldRef Name="Body" />
     <FieldRef Name="ID" />
</FieldRefs>

<DisplayPattern>
     <HTML>&lt;span style="display:none;" id="el_</HTML>
     <GetVar Name="WPQ" />
     <HTML>_</HTML>
     <Field Name="ID" />
     <HTML>"&gt;</HTML>
     <Field Name="Body" />
     <HTML>&lt;/span&gt;</HTML>
     <HTML>
     &lt;script type="text/javascript"&gt;
     $(function()
     { var mySpan = $('#el_</HTML>
     <GetVar Name="WPQ" />
     <HTML>_</HTML>
     <Field Name="ID" />
     <HTML>');
       var myShortText = $(mySpan).text().substring(0, 20); 
       if ($(mySpan).text().length &gt; 20)
         myShortText += '...';

       $(mySpan).show().html(myShortText); });
     &lt;/script&gt;</HTML>
</DisplayPattern>

Notes
  • If you prefer to not escape the brackets you can use CDATA tags: <HTML><![CDATA[<b>hello</b>]]></HTML>
  • GetVar ‘WPQ’ returns the unique Web Part ID. This takes care of multiple List View Web Parts on the same page
  • You could optimize the output by extracting most of the script and placing it in an externally referenced JavaScript file
  • My JavaScript/jQuery skills aren’t the best. I’ll have to ask Jan for some jQuery pointers next time :)
 
  • Categories:


Comments

CAPTCHA Image Validation