HTML Calculated Column: solutions for SP 2010 (Part IV)

This series assumes that you are familiar with the “HTML Calculated Column” . 

Part I: fallback to SP 2007
Part II: edit in SharePoint Designer
Part III: deal with individual Web Parts
Part IV: brute force 

At the end of part III, we were left with this question: how do I know when I need to run the Text to HTML script? 

In this post I’ll provide an easy answer: I don’t know. Updates to the page can come from the asynchronous load of a calendar view,  the asynchronous update of a list view, expanding grouped items, a response to a Web service call, etc.

Not knowing when or where updates happen, my only solution is to scan the content of the page at regular intervals. Not the most elegant or performant choice, but a bulletproof approach that will cover all cases.

My sample code:

 
<script type="text/javascript">

// Copyright (c) 2010 Christophe Humbert - Path to SharePoint

// Find all Web Parts in the page
var listWP=[],calWP=[],divs=document.getElementById("MSO_ContentTable").getElementsByTagName("div");
var count=divs.length;
for (i=0;i<count;i++) {
try {
if (divs[i].id.indexOf("WebPartWPQ")==0){
if (divs[i].innerHTML.indexOf("ViewDefault_CalendarView")>=0) {
// Calendars
calWP.push(divs[i].id);
}
else {
// Other Web Parts
listWP.push(divs[i].id);
}
}
}
catch(e){}
}

function TextToHTML(NodeSet, HTMLregexp) {
var CellContent = "";
var i=0;
while (i < NodeSet.length){
try {
CellContent = NodeSet[i].innerText || NodeSet[i].textContent;
if (HTMLregexp.test(CellContent)) {NodeSet[i].innerHTML = CellContent;}
}
catch(err){}
i=i+1;
}
}

var regexpA = new RegExp("\\s*<([a-zA-Z]*)(.|\\s)*/\\1?>\\s*$");
var regexpTD = new RegExp("^\\s*<([a-zA-Z]*)(.|\\s)*/\\1?>\\s*$");

var WP = new Object;

function UpdateWP() {
if (calWP.length>0){
for (i=0;i<calWP.length;i++) {
WP=document.getElementById(calWP[i]);
if (WP.innerHTML.indexOf("&lt\;")>=0) {TextToHTML(WP.getElementsByTagName("a"),regexpA);}
}
}
if (listWP.length>0){
for (i=0;i<listWP.length;i++) {
WP=document.getElementById(listWP[i]);
if (WP.innerHTML.indexOf("&lt\;")>=0) {TextToHTML(WP.getElementsByTagName("td"),regexpTD);}
}
}
// Check every 200 ms, forever
setTimeout("UpdateWP()",200);
}
UpdateWP();

</script>

The beginning of the script is taken from part III.

Note that I have included a quick check – if the Web Part doesn’t contain any “<” character then there’s no need to run the full Text to HTML function.

The 200 ms interval is a trade off between refresh needs (we hope that the naked eye won’t even notice the HTML strings) and browser performance. For IE 6, you may have to increase this number.

Like the other articles in this series, consider this sample script as experimental and handle with care.

In the next episodes, we’ll try to be more subtle, and provide optimized routines to address specific situations.

Advertisements

71 thoughts on “HTML Calculated Column: solutions for SP 2010 (Part IV)

  1. Pingback: Tweets that mention HTML Calculated Column: solutions for SP 2010 (Part IV) « Path to SharePoint -- Topsy.com

  2. Thanks. I tried the code above for a calendar view of a list. It did the color-coding as expected except that the box sizes for each of the items in the calendar view do not fully display vertically which results in only being able to see the time of the event and the top border. Any suggestions on how to fix? Thanks!

    Mark V.

    • Mark, I have seen this issue, and I think it is the expected behavior. It happens with plain text too, not just when using my method. I have also pointed out a couple other calendar “behaviors” in a previous post.
      Have you tried forcing the height of the calendar Web Part?

      • Yup, I tried forcing the calendar webpart to have a height of 500px, it just gave me blank space below the actual calendar. It just funny cuz in SP2007 it worked perfect! 🙂

      • I, too, am wondering how to control the height of a single calendar item in the month view of the calendar.

        The script works great… my eye does see the HTML code flash a bit before it becomes the rendered HTML. But I am sure my end users won’t notice.

        I’ve even tried silly things like wrapping the HTML in a div tag and added inline styles to force the height.

        Any insight?

      • Mark, I just tried and everything looks fine. Anyway, if I understand correctly you are testing SP 2010, so v2.1.1 will not work for you. Use the sample code above instead.

    • Hello Christophe,
      I am using SP 2010 and followied your steps on the above link but did not understand how to proceed using this post to implement in SP 2010.
      Hope that you can assist me.
      Thank you
      Yael

      • I am not a developer therefore asking if you have the code ready for SP 2010 for calendar colors that I can use?

  3. For monitoring when to fire the amazing TextToHTML code, have you considered something like what’s described in this article where the author monitors for new objects to be created?
    http://www.erichynds.com/jquery/jquery-create-event/

    This also sounds like a use for Reactive Extensions for JavaScript, but I have to confess I am largely igorant of this tool so far. (Basically, I’ve read the home page and one article.)
    http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx

    • Thanks for these useful pointers Kevin.

      For jQuery and duck punching: the short answer is yes, I have considered this. But these are difficult topics, and I could definitely use some advice here. I’ll write a post about what I’ve done so far.

      As for the reactive extensions: I didn’t know about this tool, I’ll look into this. I have already investigated some .Net specific tools (something that libraries like jQuery don’t cover). Here again I’ll dedicate a post to .Net options.

      One difficulty is that SharePoint uses several different methods to update the page content asynchronously (not necessarily AJAX for example), so it’s hard to find a one-fits-them-all approach.

      Again, I could definitely use some advice here. Feel free to chime in to share your knowledge!

  4. Christophe,

    First let me thank you for your efforts with this and your other informative articles. I just upgraded to SP2010 Foundation from WSS 3.0 and just finished getting my event calendar color coded using this method. I had it working perfectly under wss 3 again thanks largely to mix of your efforts and the video tutorial at endusersharepoint.com( who basically used your method).
    I do have what I hope is a minor issue that I hope you or one of your readers could help me with. The events are colord fin based on my nested criterias, however the rollovers in the default view and the event summaries in the day view are showing up as raw html. Is there something I can do or something I have done wrong? Any help would be greatly appreciated to resolve what is essentially a nuisance. Please if you can help me bear in mind I am not a programmer – just a direction follower with a basic undersanding of vb and html. Thanks again for what you’ve done for the rest of us and for any assistance you may offer. I would be willing to provide screenshots and my customized formulas if you needed them to help me out.

    Shane Hale

    • Shane, I found the time to look at the rollover issue, and here is how I fixed it:
      – in the script, look for this line:
      NodeSet[i].innerHTML = CellContent;
      -replace it with:
      NodeSet[i].innerHTML = CellContent;
      NodeSet[i].parentNode.parentNode.title=NodeSet[i].innerText || NodeSet[i].textContent;

      • Hi Christophe, I just made the code replacement as you advised to tidy up the rollover text, and what I now get in the rollover is the item title 2x with no space between. I checked several times to make sure I wasn’t missing something key, and can’t figure out how to fix. Can you advise?

        • I’m not sure if this is still an open issue but the way I resolved the mouse-over tooltip issue was by setting the “Title” property of the outer span tag element of my “Display” column. For example, in my calendar I wanted the Title of the event to be displayed as the hover/mouse-over tooltip. The formula I used is listed below:

          =” “&Title&””&Title&””

          Hope this helps.

        • Oops I my formula was stripped out of the previous post. Here is a snippit that should get you on the right path.

          …. span Title='”&Title&”‘ …

          Where &Title& is the name of the column you want to display.

        • Okay, one more time. This time I will use a code block.

          ="<span Title='"&Title&"' style='position:relative;display:inline-block;width:100%;'><span style='width:100%;display:inline-block;border:1px solid "&Color&";position:absolute;color:"&Color&";'> "&Title&"</span><span style='display:inline-block;width: 100%;background-color:"&Color&";border:1px solid;z-index:-1;filter:alpha(opacity=20);opacity:0.2;'>"&Title&"</span></span>"
          
  5. Pingback: Tutorial: add color coding to your SharePoint 2007 calendar in 15 minutes « Path to SharePoint

  6. Hi Chris,
    Thank you for your work!

    For SP2010, in a custom list (let’s call it “N1”), I did the following:

    in default view -> Site Actions -> edit page -> add web part -> upload -> select TextToHTML-v2.1.1.dwp -> add web part again -> pick TextToHTML-v2.1.1.dwp -> move it to below the “N1” web part -> done.

    The text is displayed as html OK, but the following menu disappeared:

    – List Tools (with items/list sub menu which you can click)
    – Views menu (to the right of “N1” should have “All Items”, with pull down arrow)

    Am I missing something?

    Sincerely

  7. Hi Christophe – this worked perfectly for me in SP 2010 – I looked at your 2007 and tried for a long time to get it to work, then I found this.
    Thanks for all of your great hard work!

  8. Hi Christophe –

    Your site has been a huge asset to me. Thank you for your great work! I did want to let you know that although I eventually got your above revised script working with my SharePoint 2010 implementation, I had trouble doing so until I figured out that the custom master page on which my site is based did not in fact have a table defined with ID MSO_ContentTable. It only was using MSO_ContentDiv. Once I edited the master page to encapsulate my mainContent area in a table within MSO_ContentDiv, and gave that table the MSO_ContentTable ID, it worked like a charm. Not sure how many people may have run into that issue. My custom master page is based upon the SharePoint “nightandday.master” page which also only uses MSO_ContentDiv and does not define an MSO_ContentTable.

    • Heather, thanks for this important feedback.

      Solutions like the HTML Calculated Column are CPU intensive for older browsers (IE6, IE7). I am trying to optimize the script, but sometimes I am too specific.
      In future solutions, I am going to include more fallback options. Modern browsers on standard pages will be lightspeed fast, while older browsers and specific layouts will still be in the game. I am currently working on a charting solution based on this concept.

  9. Christophe,
    I did a simple test, by stripping everything between:

    and I’m still having the same problem that some of the menu choices on the top are gone as soon as I add TextToHTMLlite-v2.1.1.dwp

    Is xml schema in TextToHTMLlite-v2.1.1.dwp not suitable for SP 2010?
    I’m really new to web parts, and this may be a stupid question, can any one help?

    Thanks!

    • what i meant above was stripping everything between “CDATA”
      (that itself got stripped in my post…)

      • I am not sure which menu choices Jim was referring to.

        The view menus within the breadcrumbs disappear as soon as you have more than one Web Part in the page. This is the expected behavior and happens with any Web Part. It is not linked to the script itself. To avoid this, what you could do is put the script directly in the page or the Master page.

  10. In a SP2010 “out-of-the-box” calendar there appears to be a standard event background color of pale green. If the code listed above is applied to the calendar, the display is the code color over the standard background color of pale green. Does anyone know if there a way to add to the style code in the Calculated Display column that will override that pale green color?

  11. Mark, Kathy and Earnie: the SP 2010 calendar is very complicated, both in structure and style. And it has a couple bugs, so there’s no guarantee that it will last, at least in its current form.
    It seems that styles are added both via a stylesheet (static+dynamic) and via JavaScript. So it is not easy to overwrite.
    If you want to experiment with it, here are the classes for the monthly intraday events: ms-acal-item, ms-acal-selected.

    • Christophe,

      Thank for your reply. I messed around with the ms-acal-item and ms-acal-selected, and saw miniumal results. While those two classes seemed to have some effect (background colors), I was unable to affect the height of the item. The information (whether text or layout) is still truncated once it exceeds the one line height.

      Do you know off hand the other CSS classes involved with rendering this calendar?

      See a screenshot of the problem here: http://tinyurl.com/2fpxbk4 on my blog at SharePointPanda.com

      • Changing the height will be difficult, and may not give the result you expect. The SP calendar is actually made of two layers, the dates in the background and the events as overlay. Changing the overlay size will not help much.

        • It would be awesome if you could do this. 🙂

          My HTML contains image thumbnails which are being cropped due to the fixed line-height.

          I have fudged this (only because all my images are the same height) by modifying the CSS as shown below.

          .ms-acal-summary-itemrow td div, div.ms-acal-item {height: ???px !important}

        • I have also added some jQuery to the TextToHTML function which removes the annoying text after the item hyperlink.

          function TextToHTML(NodeSet, HTMLregexp)
          {

          }
          //remove text after hyperlink
          $(“div.ms-acal-mdiv”).contents().filter(function () {
          return this.nodeType == Node.TEXT_NODE;
          }).remove();
          }

  12. Earnie: did you try reducing the timeout interval, to 100 ms for example?

    I have other solutions for specific situations, but I can’t afford to publish and support them on my blog. I’ll soon offer an online workshop on this topic.

  13. Pingback: b r e n d a n n e w e l l . c o m » Colour coded SharePoint 2010 Calendar

  14. Works perfectly for me, Christophe. Thank you once again for working thru the SharePoint 2010 issues. By the way, I also tried this script in SharePoint 2007 (to get these changes into production prior to a migration weekend). As you probably expected, it works there as well.

  15. The hyperlink of the event displays the weired text and doesn’t look good. Although it takes the control to the selected event but the tooltip should be corrected. The reason could be being the Display column set as Display column in the list settings. Please suggest, how to oversome this problem.

  16. Christophe, I was able to implement your solution (thank you!) as we migrated to SP 2010 and it worked fine except in one regard. When I hover over an item in the 2010 calendar, both for timed and all day items the displayed text includes the time/date range, and then the full text of the html used to generate the contents and appearance. I considered adding a hover value to the calculation, but I actually suspect I need to force the script to run against the system default hover value instead.

    My jscript is not up to the task. Have you run into this yourself or is this something new?

    Thank you, Elena

    • Elena, check out the comments section of the tutorial. There is some information on how to fix this issue.

      Did you try including a hover value in the calculation? I believe it should also work.

      • Thank you Christophe. Kevin’s comment about setting the Title property of the outer span was what made it click for me. I had initially semi ignored that portion of the comments as rollover != mouse hover on first glance. My mistake. Once I set the Title property to use a more elaborate calculated title with all but the description incorporated, the front page mini does just what we wanted it to.

  17. Christophe, this is awesome. Thanks for the simple solution. I have it all working correctly along with the hover over/tool tip for the event. However, when a user clicks on the item to view the properties, it doesnt pop up in a dialog box and it also shows the raw html calculated field in the view properties. Any suggestions to hide that field from the user and also ensure the dialog box pops up isntead of opening in a new page? I have made sure the advanced options in that library have dialog box check as yes.

    • For the view properties, you can either add the same code, or set the field as hidden in the content type properties.

      I am not sure about the popup, I’d need to take a closer look.

  18. Regarding the tooltip rollover problem… I tried all of the recommended solutions above to no avail. I finally ended up revising Kevin’s suggestion (August 2, 2011 at 5:02 pm) with the below:

    ="<span Title='"&Title&"' style='position:relative;display:inline-block;width:100%;'><span style='width:100%;display:inline-block;border:1px solid "&Color&";position:absolute;color:"&Color&";'> "&Title&"</span><span style='display:inline-block;width: 100%;background-color:"&Color&";border:1px solid;z-index:-1;filter:alpha(opacity=20);opacity:0.2;'>"&Title&"</span></span>"
    
    • Revised Code:

      ="<span  Title='"&Title&"'</span> <span style='position:relative;display:inline-block;width:100%;'><span style='width:100%;display:inline-block;border:1px solid "&Color&";position:absolute;color:"&Color&";'> "&Title&"</span><span style='display:inline-block;width: 100%;background-color:"&Color&";border:1px solid;z-index:-1;filter:alpha(opacity=20);opacity:0.2;'>"&Title&"</span></span>"
      
      • Hi. Hope you can help. I am trying to add the snippet above to the original script from Christophe but am struggling where it should go. Could someone please help?

        Thanks

        PS Christophe – thanks for sharing all you do.

        • Use this script exactly the same way you used the older ones (and refer to the older posts for more details, for example the tutorial on color coded calendar).

  19. Pingback: SP « ShowMeTheData

  20. Christophe, the original 2007 solution seems to work fine in the 2010 v3 mode with the only exception being grouped list views that are collapsed by default. Would you recommend using the original script where it works and the new one in collapsed grouped list views, or would you just recommend using the 2010 script for everything?

    • Good question. The old script is lighter (it runs just once, not in a loop) so I like it better for simpler cases, or one of the other techniques I have described in previous posts (…or upcoming ones 😉 ). For calendars however, the loop is the only bulletproof method I’ve seen so far (covering in particular cases when you have more than 3 items in a day, or when you need to switch between months).

  21. I know this post is a couple years old now but just wanted to see if there are any updates coming form the SharePoint Guru!? Manily the Rendering of Calculated columns in Datasheet View in SharePoint 2010. I know you said that TextToHTML will not work with Datasheet View but would like to know if you have thoughts of another solution to this.

    I am displaying images in a calculated column depending on the value of another Status column which is a choice column and Today’s date! It works create in Standard View but I would like to get it to work in Datasheet View too, just like it does for the Document Type Column. i.e. when you have a PDF, Word Doc, Excel file etc in a Document Library, then switching to the Datasheet View renders these images nicely. It even produces proper filtering with the Text! I would like to do the same for my calculated columns.

    I look forward to your feedback.

    • Right, I’ve always said that the datasheet view was proprietary code and there was nothing I could do about it. Now, in recent years Microsoft has put more emphasis on html, and I see changes in the datasheet view in SharePoint 2013. But I haven’t had much time to play with this yet.

  22. i followed the article and can get the color coding in sharepoint 2010 fine. I do run into a problem that when i launch the calender, the ribbon is not there and i have to click in any of the event field to get the ribbon and then i can change the calender views. Any ideas to fix that, please let me know. TIA

    • Hi,
      Did you just past the sample code of Christophe in a content web part? without modification?
      I simply add the webpart with the code in my calendar page that was worked on the 2007 SharePoint version, but there is no change…

    • muhammad, this is the expected behavior. As soon as you have more than one Web Part on a page, the page waits for you to select a Web Part before displaying the related ribbon.

  23. hello Christophe,

    I have tried the above script in SP 2010 calender, but it is giving me error saying that getElementById(…) is not found. Can you help me here.

  24. Hello Christophe, thank you for this great blog. I managed to get the calendar events being displayed in different colors. Now my next step would be to relate the color behavior not to category but to the author of that calendar event. Modifying the view allows me to display “created by” info, but for some reason that column is not accessable in the EVENT content type, and thus can’t be called in a formula that combines your color code, title and author. There must be a way to retreive that column as it is THERE!!! Its driving me nuts and I have scanned half the Internet. Everybody who uses the shared Calendar in Sharepoint steps on this need and I haven’t found any solution. The Calendar is connected and populated through Outlook.

    • I found I needed to create a content type for the calendar based on the event content type but with my additional fields in order to get full access to all the fields. The downside of this is that it can’t be synched to outlook calendars.

  25. The same script can be made 2013 compatible by simply replacing MSO_ContentTable with DeltaPlaceHolderMain.

    • Thanks for sharing! This will be especially useful for calendars. For lists, the new CSR (Client-Side Rendering) will make things easier.

      • I’d hoped that CSOM and CSR would make things easier but my experience with JSLink so far has been less than productive. :\

        I will stick with good old jQuery for now.

        The main issue I’ve encountered is that the document ready function gets called too soon (before the list view rendering occurs). This usually means applying a delay and a check in the way you have done.

        Alternatively I also add an Update View button with a click handler that fires UpdateWP or other custom function.

        • I’d love to continue this discussion offline, feel free to get in touch with me (Christophe@PathToSharePoint.com).

          I’m glad you mention the issue with document ready, because… I’ve always been convinced it would cause issues in SP 2013, but so far I haven’t been able to set up a test case to prove it! I’d be interested to see your example (maybe even publish a post if you want to write one). This would be one of the reasons why I would go with CSR rather than jQuery.

          You might have read my recent posts about my SPELL program. SPELL doesn’t rely on jQuery document ready, and has its own methods (node ready). I did this to anticipate issues with document ready, even if what I do is still not perfect (case of partial refresh for example).

      • Hi All, I am working on SP 2013 and the script does not work with the //document.getElementById(“DeltaPlaceHolderMain”).getElementsByTagName(“div”);
        Could someone please share the script to be used for SharePoint 2013?
        Thank you very much!

        • Hello I have been reading these posts and the other items on the site for the past two days, since I use the TexttoHTML2.1.1.txt script a lot on my MOSS2007 pages and they are doing nothing at all on the SP2013 pages. Could I add my voice to Mima’s to say “could someone please share the script to be used for SharePoint 2013?”? I use the she script for things like calculating hyperlinks, creating color coded flags in lists and such and if this won’t work, I face a ton of rework.

  26. Pingback: HTML Calculated Column + Client-Side Rendering | Path to SharePoint

  27. Reblogged this on Reckless SharePoint and commented:
    This post by Christphe contains his most recent HTML calculated column script, which I will be referencing in many of my posts and videos. To make the script work in SP 2013, replace “MSO_ContentTable” with “DeltaPlaceHolderMain” per the comment by Panoone on June 12, 2013.

Comments are closed.