Truncate text in list view and add mouseover preview

Change log
19.06.2015
v1.2 for SP2007: By request fixed a bug occurring when using this in a list view with multiple web parts from the same list (same fieldinternalname), and the column position of the field is not the same for all the web parts.

19.07.2014
v1.2 for SP2010 and 2013: Small update to address a bug in IE9 and add support for paging in SP2013. Please note that I have not gone all in here – it is updated only to try to fix these bugs so there might be bugs I have not addressed. Use this code as a starting point and adapt it as you like.

08.12.2011
I have updated to v1.1 to fix a bug preventing the use of FieldInternalName for addressing the fields. Thanks to Ed MacIntosh (@cosmo132) for finding the bug.

I have previously done this article Multi line text field in list view: Shorten text and add hovereffect to view full text.

This post is an updated version to support both SharePoint 2007 and SharePoint 2010.

Features

This solution will shorten any text column (single line or multi line) in a list view to a preset length, and append “…” to indicate that the text is truncated. If the text is shorter than the “trigger length”, the cell is skipped.

How to set up

Go get jQuery v1.6.4 from here.
Note that this is NOT the latest version. I have not had the time to find out why v1.7+ does not work.

Download the code for the file “TruncateTextInListView.js” from here Note the different versions for SharePoint 2007 and SharePoint 2010.

Upload both files to a shared document library – or a folder in the root of the site (created with SharePoint Designer). Ensure all users have read access to the location.

Put a CEWP below the list view web part, and insert this code:

<script type="text/javascript" src="/test/English/Javascript/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/TruncateTextInListView.js"></script>
<script type="text/javascript">
	
function init_TruncateText(){
	truncateText('MultilineText',50,'');
}

</script>

Note:
You must change the “src” attribute of the script tags to point to your local copies of jQuery and “TruncateTextInListView.js”.

Parameters for the function “truncateText”

  • fieldName: The FieldInternalName for single line text fields or display name for Multi line text fields.
  • initialLength: The number of character to display.
  • inPlaceHoverText: This argument is optional and can be a text to show in place of the original text – like “hover to read”.

Ask if something is unclear.

Alexander

84 thoughts on “Truncate text in list view and add mouseover preview”

    1. Thanks for pointing this bug out – I guess i was in a hurry when i posted this code and did not test it thoroughly.

      See updated code.

      Alexander

  1. Hi Alex,

    I tried your given script but got fail. I am using MOSS. It seems URL may be the problem. I created document library (JavaScript) in my site and gave URL as below in CEWP.
    src=”/JavaScript/jquery-1.7.1.min.js”.

    I also created Multi line column with Plain and Rich text type.

    Pls advice.

      1. Hi,

        The solution is super (thanks Alexander).
        Chintan, if you need to use it with the newer jQuery just modify the selector to:

        var colIndexPlus1 = colIndex + 1;
        //$(“table.ms-listviewtable tbody:not([id^=’aggr’]) tr:has(td.ms-vb2) >td[cellIndex=” + colIndex + “][beenthere!=1]”).each(function(){
        $(“table.ms-listviewtable tbody:not([id^=’aggr’]) tr:has(td.ms-vb2) > td:nth-child(” + colIndexPlus1 + “)[beenthere!=1]”).each(function(){

        Regards
        Michal

  2. Hi Alexander,

    Can you help me troubleshoot?

    I downloaded jQuery v.1.6.4 and the the code for the file “TruncateTextInListView.js”, uploaded both to the Shared Documents Library on the site. I added the list to a new page and the CEWP below it. I pasted the following code into the HTML source of the CEWP:

    function init_TruncateText(){
    truncateText(‘MultilineText’,50,”);
    }

    I also tried uploading this code as a .txt file and adding a link to the file from the CEWP. And I tried it in a different library (in case the “Shared%20Documents” part of the link was messing things up).

    The list in question is a Links List. I changed the title of the multi-line Rich Text column to Summary instead of it’s original title Comments.

    Any ideas why it’s not working? Wondering about maybe the jquery download because I’m not sure how to test if that’s working.

    Thanks!

  3. Hi Alex,

    When i add referrence to TruncateTextInListView.js, it starting throwing error “Internet Explorer can not display the page”.

    Please help.

  4. Hi, I am using 8.0.6001.18702…
    No, nothing special.. i have two web server and 1 db server and 1 index server….
    In IE 6 or 7 it is throwing an error Operation Aborted and then Internet explorer can not display the page
    In IE 8, it is throwing two java script errors…
    1. HTML Parsing error. Unable to modify the parent container element before the child element is closed. Line 0
    2. Object expected. Line 11 char 2

    1. Hi,
      Try to change line 22-24 from

      $(document).ready(function(){
      	init_TruncateText();
      });
      

      to

      _spBodyOnLoadFunctionNames.push('init_TruncateText');
      

      Alexander

      1. Hi Alex,

        It did not work too 🙁
        it is still throwing java script error “HTML Parsing error. Unable to modify the parent container element before the child element is closed(KB927917). Line 0 char 0”

    2. Hi,
      Try to move this line:

      $("body").append(cssBuffer.join(''));
      

      Into the document ready block like this:

      $(document).ready(function(){
      	$("body").append(cssBuffer.join(''));
      	init_TruncateText();
      });
      

      Alexander

      1. Now no javascript error but nothing is working… 🙁
        Neither truncating and nor mouse hover working…

      1. Hello Alex,

        this code throw an object reference error in IE 7 and no error in IE 8 but do not work as well.

        $(document).ready(function(){
        $(“body”).append(cssBuffer.join(”));
        init_TruncateText();

        });

        as u asked i add one alert above it, alert is getting called but then page throws object reference error.

        $(document).ready(function(){
        alert(‘hi’);
        $(“body”).append(cssBuffer.join(”));
        init_TruncateText();

        });

    3. Try REMOVING this from the “TruncateTextInListView.js” file:
      [sourcecode language=””]
      var cssBuffer = [];
      cssBuffer.push("<style type=’text/css’>");
      cssBuffer.push("span.hideMe{");
      cssBuffer.push("visibility:hidden;");
      cssBuffer.push("}");
      cssBuffer.push("</style>");

      $("body").append(cssBuffer.join(”));

      then ADD this to the bottom of your CEWP code:
      [sourcecode language=””]
      <style type="text/css">
      span.hideMe{
      visibility:hidden;
      }
      </style>

      I’m not sure if this helps, but without being able to recreate this error it’s a bit difficult to pinpoint the cause.

      Alexander

      1. Alex,

        For feedback:
        I got this problem with 1 IE8 installation (worked fine on all other IE,Chrome and Firefox installations). Your solution worked. I didn’t find:
        [sourcecode language=””]
        …in the js file so ignored this bit

        I don’t know the cause but can confirm this did fix it for me.

        I’d prefer not to have a custom js file, so I might try and work out some format of try/catch, so that it doesn’t break the page if the same happens again

  5. Hi Alexander,
    I’m trying to get this up and running on SP2010 Foundation. I have added the CEWP below my list. I have editted the src statements to point to my server using both relative and absolute pathing. I have grabbed 1.6.4 from jscript. I have looked up the FieldInternalName for my multiline field and put that in the CEWP. Not sure why I’m not getting any response from the system. Here is the text in the CEWP where Scripts is a document library in the same site:

    function init_TruncateText(){
    truncateText(‘Notes’,50,”);
    }

    Any thoughts?

  6. I can’t seem to get this to work with my discussion. I have a standard SharePoint discussion board with a newsletter view that I want to truncate. I am in WSS 3.0. My code is:

    function init_TruncateText(){
    truncateText(‘Body’,50,’hover to read’);
    }

    This is located in a CEWP just below the discussion board on a multi-web part page. Body is both the internal and display name of the field.

    Do you have any suggestions?

    1. Hi, This solution is not tested in a newsletter style view. You should test it in a plain list view, and ensure you have the CEWP below the list view web part. Alexander

      1. Hi Alexander,
        Thanks for this, it works fine in the default view, just as described, but not in the newsletter view.

  7. I noticed, if I change the list default style, it affects this script. Having it in “Default” style makes this script non-functional. Switched to “Shaded” and this script works.

    Also, if you have “Grouping” turned on, it stops functioning as well.

  8. Hi Alex,

    I would love to use this solution, but it isn’t having any effect when I use it in SharePoint 2010. I’m using a custom list to test the script, with one single line of text column and one multiple lines of text column. I don’t get any errors when the page loads, but the text is not truncated and there is no effect from hovering over either column (I tested each column separately). The code from the CEWP is below. Any suggestions on what I can do to debug the solution?

    function init_TruncateText(){
    truncateText(“SingleLineTest”,25,””);
    }

    Thanks,
    Isaac

  9. Found out, why the script is not working with newer jQuery versions: Replace this line

    $(“table.ms-listviewtable tbody:not([id^=’aggr’]) tr:has(td.ms-vb2) >td[cellIndex=” + colIndex + “][beenthere!=1]”).each(function(){

    by this line

    $(“table.ms-listviewtable tbody:not([id^=’aggr’]) tr:has(td.ms-vb2) >td:nth-child(” + (colIndex + 1) + “)[beenthere!=1]”).each(function () {

    (note the use of the nth-child selector instead of colIndex)

    Now the script works with jQuery 1.8.3 AND it works with list view webparts that are embedded in webpart pages together with other webparts (the original script does not work in this case).

  10. I was able to successfully get the code to work on a SharePoint 2010 site with the look and feel of 2010 but I was also trying to use the same code on the same server for another site that still has the 2007 look and feel but nothing text does not truncate that the mourse over does not do anything either. Should you be able to use the same code no matter what look and feel you have?

    1. I was able to figure it out. I had to use the 2007 version of the code on the 2010 SharePoint server for the 2007 Look and Feel of the site. I still had to make the following code modification to the 2007 version in order for the code to work properly like suggested earlier for the 2010 version:

      $(document).ready(function(){
      	$("body").append(cssBuffer.join(''));
      	init_TruncateText();
      });
      
  11. I was wondering if this should also work with rows that are collapsed. I had tried to expand a collapsed column, and it did not function properly. Just curious if I am doing something wrong, or if it lacks this functionality. Other than that it is amazing.

  12. I am mainly interested in truncating long announcements. The roll over is the icing on the cake. I am having an issue with the roll over text showing up below the announcement. It essentially drops down to the second row. Is there something I need to change for the roll over text to show directly above the truncated text? Or, if I had to, can I disable the roll over all together.

    Thanks for this and also your support.

  13. Hi Alex,

    I am getting javascript error throwing in my IE 8.
    The error message is,

    Webpage error details

    Message: Object expected
    Line: 21
    Char: 1
    Code: 0
    URI: http://blrksvm0195srv:5006/sites/ClientCaseRepository/Documents/TruncateTextInListView.js

    The script which is at line number 21 is,
    $(document).ready(function(){ $(“body”).append(cssBuffer.join(”)); init_TruncateText(); });

    Could you please tell me why it is throwing error..or any suggestions from your side is helpful for me.

    Thanks in advance!

  14. Alex,
    First off let me thank you for such useful code, it’s helped me greatly reduce the amount of text on screen and made my boss happier.

    Our company just did the big migration to 2013 and I’m having trouble getting the code to properly work. We went from 2007 straight to 2013, but I was able to test in 2010 environment once and your code worked. I know some things work across different versions, have you or anyone that commented before used this in 2013?

    Thanks in advance!

    Brett

  15. Hello Alexander,

    first of all, thank you! That´s what Im looking for.
    But Im new to SharePoint and tried to integrate it.

    I made a library uploaded the files.
    I made Custom Editor and put the Script there.

    But nothing happens to my list.
    I dont know exactly where I made the mistakes..

    Maybe you can help me, would be really nice.

    Max.

  16. Thank you for keeping this solution in yoru achives! My company is still using sharpoint 2007 and this works great!.

    I can also verify that Michal and Ros solution does work for sharepoint 2007 and jQuery 1.10.2 after retyping all the quotes in notepad as this comments field messes them up :).

    $(“table.ms-listviewtable tbody:not([id^=’aggr’]) tr:has(td.ms-vb2) >td:nth-child(” + (colIndex + 1) + “)[beenthere!=1]”).each(function () {

  17. Hi,

    Thanks for this great bit of code. I am trying to truncate 2 columns, but I can not get them to work together.

    Only 1 column works. Any suggestions?

      1. Hi,
        I tested this (in SP2010 though, but I don’t think this should matter) but it worked for me with two columns in the same view.

        Can you post the code you use to trigger the function?

        Alexander

      2. Webpart code:

        function init_TruncateText(){
        truncateText(‘Resolution’,50,”);
        truncateText(‘Description’,50,”);
        }

      3. snippet of js file:

        function truncateText(Description,initialLength,inPlaceHoverText){
        $(“.ms-viewheadertr th[class^=’ms-vh2′]”).each(function(){
        if($(this).attr(‘class’)===’ms-vh2-nograd’){
        if($(this).text()===Description){
        colIndex = this.cellIndex;
        }
        }else{
        if($(this).find(‘table:first’).attr(‘name’)===Description || $(this).find(‘table:first’).attr(‘DisplayName’)===Description ){
        colIndex = this.cellIndex;
        }
        }

        });

        function truncateText(Resolution,initialLength,inPlaceHoverText){
        $(“.ms-viewheadertr th[class^=’ms-vh2′]”).each(function(){
        if($(this).attr(‘class’)===’ms-vh2-nograd’){
        if($(this).text()===Resolution){
        colIndex = this.cellIndex;
        }
        }else{
        if($(this).find(‘table:first’).attr(‘name’)===Resolution || $(this).find(‘table:first’).attr(‘DisplayName’)===Resolution ){
        colIndex = this.cellIndex;
        }
        }

        });

        if(typeof(colIndex)===’undefined’){
        return; // Target column not in view
        }

  18. Hello,
    great compliments for all the help you give.

    I’m testing:
    truncateText 1.2
    Sharepoint 2013 Online
    jquery 1.11.1

    I made the changes to bring up the code window by adding the z-index: 9999

    I added the icon with “…” with

    On list also works well with multiple columns.
    I wanted to ask for help with the problem of Web Parts

    init_TruncateText function () {
    truncateText (‘description’, 50, ”);
    truncateText (‘Notes’, 50, ”);
    }

    I created a wiki page with different lists and not all fields (description and notes) are truncated.
    Some lists are no other

    Help me, I can not solve the problem

    Thank you

      1. Hello,

        thanks for the answer.
        I looked at the link, very crude approach.

        Yours is much nicer.
        You have no ability to modify your code?
        I do not know much about the language

        Thank you

    1. Hi,
      The problem with “my” solution in SP 2013 is that the rendering of the list views are asynchronous – this is most likely the reason that this does not work. Another thing is that it looks for specific DOM elements in the page to “tap into”, and this may change for new versions or for example in a wiki page.

      Did you test the solution I linked to? – it will be more robust as this is the way you are supposed to do something like this in SP2013.

      You can try using my solution by delaying the function call and see if the script works.

      setTimeout(function(){
      init_TruncateText function () {
      truncateText (‘description’, 50, ”);
      truncateText (‘Notes’, 50, ”);
      }
      },1000);

      Please note that this delay will cause the full text to flash before it is truncated.

      Alexander

  19. Hi, thanks for a great post.
    I have this solution working in SP2010 and 13, and truncating multiple list columns.
    However, I’m a little bit stuck using this solution with tabbed lists.
    I’m using EasyTabs.
    Do you have a solution for this please?
    Thanks!

  20. Hi,
    I tried to use your solution to truncate a multi people picker value with many users. It also seems to work but when I use the seeting “Name + state” for the people picker, I got a overlay of the “state”-icons in the list view. I need “Name + state” otherwise it’s not possible to filter the names in the list.
    Would be great to get a solution for this issue.
    Many Thanks!

    regards
    Dominik

    1. Hi,
      Sorry, but I have not tested this. I guess you must use the developer tools (hit F12 in the browser) to inspect the icon to find its CSS class. Then experiment with changing the z-index property to see if you can make it invisible when hidden.

      You can also use css to completely hide this icon. Unfortunately I have no code example for you.

      Alexander

  21. Hi Alexander,
    one additional question.
    I use your solution in one of our SP2013 list and it seem to work perfect. But when I have more than one page (is limited in the view) the script lost ist functionality. On the second page in the list view the text is not truncated and there is no mousover. Do you have an idea why?
    Thank you
    regards
    Dominik

  22. I am using this code in a SP2007 instance and I have multiple list views on the same webpart page. It is truncating the column in the last web part but when I move the CEWP holding the code up under another list view it still only affects the last list view. Any thoughts?

    1. Hi,
      I have not used this for several years so I cannot remember if I had it working for multiple list views in the same page. Are the list view using the same style? – it might be that some styles will not work.

      Are the list views from the same list, so that the field name is the same? – not sure if this matters, but it might.

      Alexander

      1. They are all list views from the same list containing similar columns but not all the same. Basically the master list has 20 columns and each view may show 5 at a time for a different purpose. They al share a similar column though named “Comment.” That is the column I am attempting to trucate. This is an amazing solution BTW. Thank you for the quick response!

Leave a Reply