11/19/2008

SharePoint: Color Coding SharePoint Lists

Color Coding SharePoint Lists – without custom web parts or server code deployments

SharePoint does not have an out of the box way to set colors based on the data in a list or library. There are both third party web parts and open source projects, such as codeplex.com, that can color code lists, but these usually require installing code on the SharePoint web servers. In this article we will look at color coding lists just using the built-in Content Editor web part and some JavaScript.

Each list will need a slightly different fragment of JavaScript to set the colors.

Color coded calendars?

For other lists and libraries you will find examples below to:

  • Set color backgrounds for rows in task lists to show the status of the task
    Color coded SharePoint task list

  • Set colors in libraries to show approval status
    Color coded SharePoint task list (approval status)

  • Set the color of a single column based on its valueColor coded SharePoint list(task status)


To add the Content Editor web part and JavaScript:

  • Display the view to color code (each view will need its own web part and JavaScript)
  • Add a Content Editor web part
    • Site Actions, Site Settings, Edit Page
    • Add a Content Editor web part and move it below the calendar web part
    • Move this web part so it is below the list you are color coding
    • Click in the web part, click Edit, Modify Shared Web Part, and in the Appearance section change "Chrome" to "None".
  • Add the JavaScript
    • Click Source Editor
    • Type or paste the JavaScript (examples below)

Example 1: Set the background color of a row based on data in the row

To color code a row all we need is:

  • A column to check (such as the Task Lists' status column)
  • JavaScript to find this item in a table TD tag
  • JavaScript to assign a style to the TD's parent row (TR)
  • And of course, the web part described above to hold the JavaScript

Here is the example for a task list:

 

<script type="text/javascript" language="javascript">
  var x = document.getElementsByTagName("TD") // find all of the TDs
  var i=0;
  for (i=0;i<x.length;i++)
  {

    if (x[i].className=="ms-vb2") //find the TDs styled for lists
    {

      if (x[i].innerHTML=="Not Started") //find the data to use to determine the color
      {
        x[i].parentNode.style.backgroundColor='white'; // set the color
      }

    //repeat the above for each data value

      if (x[i].innerHTML=="In Progress")
      {
        x[i].parentNode.style.backgroundColor='lightgreen'; // set the color
      }

      if (x[i].innerHTML=="Completed")
      {
        x[i].parentNode.style.backgroundColor='lightblue'; // set the color
      }

      if (x[i].innerHTML=="Deferred")
      {
        x[i].parentNode.style.backgroundColor='lightgrey'; // set the color
      }

      if (x[i].innerHTML=="Waiting on someone else")
      {
        x[i].parentNode.style.backgroundColor='orange'; // set the color
      }

    }

  }
</script>

 

Code Notes:

  • x[i] is one of the table cells (TD)
  • x[i].innerHTML is the contents of a cell (TD) (which may include additional HTML)
  • x[i].parentNode is the row containing the cell (a TR)
  • x[i].parentNode.style.stylename is used to set any valid style on the TR


Example 2: Set the color of a field based on data in the field

To color code a cell all we need is:

  • A column to check (such as the Task Lists' status column or a library's approval status column)
  • JavaScript to find this item in a table TD tag
  • JavaScript to assign a style to the TD

Here is the revised JavaScript fragment for a color coding a single cell:

if (x[i].className=="ms-vb2") //find the TDs styled for lists
{
  if (x[i].innerHTML=="Completed") //find the data to use to determine the color
  {
    x[i].style.backgroundColor='darkblue'; // set the background color
    x[i].style.color='white'; //set the font color
  }
}

125 comments:

Anonymous said...

I was trying to use the code, but I dont see any result in my List, I am using a Sharepoint Task List. No errors but no result as well.

bob said...

Great script. Thanks for making this available

Richard Lancaster said...

Mike, this works very well. Thank you for sharing this. One observation, for views that have grouping in them, the groups need to be defaulted to expanded for it to work. The colour then remains when collapsed/expanded. Makes sense when I think about it. If collapsed I guess the code doesn't find any values that match so it doesn't colour them. If you want another challenge....... how would we colour fields where the value is less than x, or between y and z, or greater than z, etc... ? Being able to do that too would be superb!! Best regards,

Anonymous said...

Out Freekin Standing!!!! Until I came across your article today....I found a whole bunch of articles telling me to do this via a custom data view created with sharepoint designer...blah blah blah.

This was extremely easy, straight forward and quick to implement!!

CAN'T THANK YOU ENOUGH!!!!
Bubba Chuck

Mike Smith said...

> I was trying to use the code, but I dont see any result in my List, I am using a Sharepoint Task List. No errors but no result as well.

Most likely a typing error. Check the bottom left of your browser to see if there is a JavaScript error icon. If so, then there is a syntax error in the JS, otherwise check the part of the JS that is matching the data in the list. Check for capitalization, "Pending" is not equal to "pending".

Mike

Ulrich Bernskov said...

Simepl hack - very useful. Thanks for sharing.
I would suggest to add the few lines of Java code to :
the revised JavaScript fragment
jsut to clarify for those who might not speak Java :-)

Mike Smith said...

If you had a problem with the above sample JavaScript, it was most likey from a typo in the color name "lightgray". It must be spelled "lightgrey". This has been fixed in the example.

Berni said...

Was looking for a solution like this about 18 moths ago - this is BRILL. Thankyou soooo much!

Anonymous said...

got it to work----thanks much !!!!

ngalli@ups.com said...

would u know why when I group things by a particular column, all my color coded cells revert back to the default

Anonymous said...

sorry if this is a dup--- color-coding not working if cells are grouped together by a particular column

Mike Smith said...

When grouping is enabled AND you set the default to Expanded, then the above JavaScript works. If the default is set to Collapsed then the JavaScript is running before the data has been downloaded. (You can confirm this by displaying a grouped task list with the groups defaulted to Collapsed, and then viewing the source of the page and searching for any of the task list data. It's not there.)

I'm looking for a way to hook in to the Expand button javascript....

Anonymous said...

Love it. I wanted to have color coding for only the cell (instead of the whole row) so I changed 'x[i].parentNode.style.backgroundColor' to 'x[i].style.backgroundColor'. That way, I was able to color code 2 columns with a seperate set of colors.

Anonymous said...

Thanks a lot. Worked like a charm!

Anonymous said...

Great.. thanks a lot.. it works perfect..

TomorrowsMan said...

Excellent script, and worked perfectly in IE8, FireFox 3.5, and Chrome 3.0 -- however I could not get results in IE6, unfortunately the legacy browser here. Any suggestions for IE6 compatibility?

Anonymous said...

Must be using a different version of SharePoint, as your instructions to match the options in our version at all.

Mike Smith said...

Anonymous,

The steps above are for SharePoint 2007, not 2003 or 2010.

Which are you using?

Also the samples are from a default Task list. You may be using a customized task list. Just change the key words to match yours.

Mike

Anonymous said...

We are using WSS 3.0 and both worked for me.

hospitalwebguy said...

We are currenting using WSS 3.0 and both are working for me. This great information and I will be checking every day for 'new' things. I would like to be able use the SharePoint calendar like the Outlook calendar, using different color 'bars' for the all day event(s). Thanks again :)

hospitalwebguy said...

In the 'Task' how do we develop a formula to make the coloring for tasks to change color as soon as the time elapses or past the due date?

akosua said...

Do you know how to set allocate a color to an entire blocks of columns in sharepoint?

I tried chaning the code but it didn't work.

Mike Smith said...

akosua,

You will need to tell me a little more about what you want to do. You want to change entire columns? As a fixed color, or dependent on a value in a row? Other?

Mike

richard said...

This is tremendous! Many thanks!

Faffe said...

Sweet! Worked at once!

steve.darcyryan said...

Mike, thatnks for the great script. It works fine with textual columns but I can't seem to get it working for numbers. Any tips on the syntax, I've tried both =="1" and ==1 but neither works for me.

Mike Smith said...

Steve,

Numbers work fine, when they are simple numbers like ID. Here's an example:

if (x[i].innerHTML=="2")
{
x[i].parentNode.style.backgroundColor='green';
}

The data type/column of "Number" displays as right aligned, so the innerHTML includes a DIV tag. The example would then be: (due to how blog comments work, you will need to replace square brackets with angle brackets)

=="[DIV align=right]123[/DIV]"

Capitalization is important in JavaScript, so to play it safe with all browsers you may want to convert the value to uppercase first:

if (x[i].innerHTML.toUpperCase()==

Let me know if this works for you.

Mike

Azam said...

Many thanks for knowledge sharing.
It was very helpful...

Anonymous said...

Thanks so much that worked perfectly.

Is there a similar method for adding a thick border to the grid cells?

Mike Smith said...

Anonymous,

Add a border around what? The entire table, a single cell?

Here's how to add a border to the entire table (the last line is the update needed):

var x = document.getElementsByTagName("TD") // find all of the TDs
var i=0;
for (i=0;i<x.length;i++)
{

if (x[i].className=="ms-vb2") //find the TDs styled for lists
{
x[i].parentNode.parentNode.parentNode.border="2"


Instead of .border you could also add any of the border styles using:

x[i].parentNode.parentNode.parentNode.style.borderColor="red"

Do a search on "CSS border style".

Mike

wmurphyhh said...

Mike - Thanks for the example. I am not a Java programmer. I was able to color code specific fields using calculated fields.
I was unable to get this script to work. Can you please instruct me on the key words to change. I assume 'ms-vb2' is the view name, but I am also unsure how to identify my view.
I am using Sharepoint v 3.0 in a list format.
Thanks

Mike Smith said...

wmurphyhh,

>I was able to color code specific fields using calculated fields.

So you got it to work on at least one list, right?


> I was unable to get this script to work. Can you please instruct me on the key words to change. I assume 'ms-vb2' is the view name, but I am also unsure how to identify my view.

'ms-vb2' is not a view name, it is a Cascading Style Sheet (CSS) class name used to link a CSS class to an HTML element. The steps in the article should work with any view of a list, and the web part and code would need to be added to each view page.

The "key words" would be the contents of the table cells such as "In Progress" and "Completed".

Mike

Anonymous said...

It works wonderfully...but when some other user runs it...he cannot see the results...we checked the IE settings too...Does different users matter or this script is user-independent?
Thanks!

Mike Smith said...

Anonymous,

> Does different users
matter or this script is user-independent?

Should not matter by user, as long as they have the same permissions to the list. Their browser could make a difference. Are you both using the same browser and version? Do some testing by having them login using your browser and you using theirs.

Mike

Anonymous said...

I have been unsuccessful at executing your code. As others, I can view the javascript code in the calendar, and it is returning the color name and the title of the calendar item, but not any color. I've checkec all the code from the source editor to the Calendartxt field. I can't seem to get the javascript to work.

Mike Smith said...

Anonymous,

The code works... so here's some things to check:

Are you working in SharePoint 2007?This example is only for 2007.

Check the capitalization. JavaScript is case sensitive.

If you copied and pasted, you may have gotten some odd formatting. Consider after pasting retyping the dashes "-" and quotes. These are often mis-copied.

If I get time tonight, I upload the text of the JavaScript somewhere and post a link from here.

Mike

mike.d.ballard said...

Mike,

I am using your code to color-code rows in my SP list and it works perfectly. I have a question though - once a row is color-coded in the list, is there a way to maintain that row's color when the list is exported to Excel? We are running SP 2007 and Office 2007.

Mike

Anonymous said...

Hi Mike,

I was able to use this on a Task List and on the Calendar but not on a Document Library. When Editing the page, Sharepoint won't allow me to move the Content Web Editor Web Part below the List View web part. I'm getting the error "The file must be checked out. YOu must first check out the document before making changes". But it's the page that I am editing. Any ideas why?

Thanks for this great tip.

Ihmunro said...

Afternoon

This is a great script.

The only issue I had was after the fact when printing - the color coded shows did not show up.

How can this be achieved ?

Iain

Mike Smith said...

Ihmunro,

That's a browser setting... In FireFox it's File, Page Setup, Print Background. In Internet Explorer it's Tools, Options, Advanced and in the Print section "Print background colors and images".

Mike

Sheila said...

Mike, the script states that if a task is due today it is "Past Due!" Is there a specific line or item in the script I can change to say if it's after today then it's Past Due? Thanks =o)

Anonymous said...

First, Mike thatnk you so much, it works great. However, I was wondering if you can tell me how to color code (single cell, not the whole row) just like you show us, but using a different field in the list instead of "Status".. ??
Let say that you make a new column name "Selections" with few choices. How can I color code a new column .. or any column besides the "Status" column..
Thank you so much Mike..

Mike Smith said...

Anonymous,

> but using a different field in the list instead of "Status".. ??

The code in this article does not care which column you are using. It just looks for key words. For example, if you had a column call Region with values like North, South, East and West, then just modify the code above to look for those four key words.

Mike

Joe B said...

Is there an adaptation of this for 2003 users?

Mike Smith said...

Joe,

It would probably work, but you would need to confirm the name of the style being used for the table cells. (ms-vb for 2007) And it probably will work if you just remove the style test line: if (x[i].className=="ms-vb2")

Mike

Anonymous said...

1000x Thank you. It's people like you Mike who increase the significance of the internet. The details in this post have been added to my arsenal of HOW TOs. Much obliged. I'd thank you with a beer if you were here in Tokyo.

Anonymous said...

Can you clour a cell if it contains the word "Red" but might not match exactly "Red". So colour red the following cells - "Red Car 2009" "Red Car 2010". Great Post BTW.

Mike Smith said...

> Can you clour a cell if it contains the word "Red" but might not match exactly "Red".

Yes, just change the JavaScript from:
if (x[i].innerHTML=="Red")

To...

-- "Red" must be the first word:

if (x[i].innerHTML.indexOf("Red") == 0)

-- "Red" can be any word:

if (x[i].innerHTML.indexOf("Red") > -1)

-- and if you want to match "red", "Red" or "RED" then convert the text to lowercase before testing:

if (x[i].innerHTML.toLowerCase().indexOf("Red") > -1)

Mike

Andreas Schmidt said...

Thanks a million that's awesome.

Just one minor thing. I have now between each line a light grey boarder to separate them (most are green so I'm safe).

Any way to make the boarder maybe black (cause black is the new white).

cheers
Andreas

Mike Smith said...

Andreas,

Sure, just add a border style to the list of style changes:

x[i].style.backgroundColor='darkblue'; // set the background color
x[i].style.color='white'; //set the font color
x[i].style.border='3px solid black'

Mike

Basia said...

This script it great! Now I want to use it on a calculated field, but it won't work. I have it working on fields with text, but I have a calulated field that figures out if a task is past due and then returns text (red, green).
Any idea?

Mike Smith said...

Basia,

Do a "view source" from the browser and search for your past due text and see if it is wrapped in any additional HTML. Calculated columns formatted as data or number with often have additional HTML in their output.

If you just want to highlight past due items then take a look at:
http://techtrainingnotes.blogspot.com/2009/03/sharepoint-past-due-late-tasks-in-task.html
and
http://techtrainingnotes.blogspot.com/2011/03/sharepoint-javascript-and-dates.html

Mike

KIP said...

Hi Mike,

Thanks for a nice solution! Did you ever find something to work with collapsed groups in a view? I reall would like the collapsed view to show when people hit the page due the number of items.

Thanks,
Kat

Anonymous said...

Mike,
gr8 work,was curious to know if the same color coding can be extended to the list while using the option "export to spreadsheet" or when using "open with access"

Mike Smith said...

Anonymous,

No, the colors won't export as they are just added to the final HTML, to the actual list. The closest you might come is to copy the data from the browser and paste it into Excel, but I think that will be messy.

Mike

Short-Term said...

I don't suppose there is any way to display colors in datasheet view in IE?

It seems Firefox only has the standard view, but IE has both datasheet and standard views. It works fine in IE standard view, but no colors in datasheet view :(

Mike Smith said...

Short-Term,

Sorry, but no. The data sheet view is an Active-X control and can't be modified with simple JavaScript.

Mike

Anonymous said...

Awesome hack..thanks!
But is there a way to chance the font size/style this way too?

Also I dont know any web programming, where can I find a list of attributes that can be changed similarly? Many thanks!

--
anonfan

Mike Smith said...

anonfan,

I don't know of a single place to find this kind of info. Two places to get a good start:

http://www.heathersolomon.com/

and my book "SharePoint 2007 and 2010 Customization for the Site Owner" here or at Amazon.

Mike

Anonymous said...

Mike, thanks for sharing your efforts. Works like a charm.

Abhi said...

Terrific! Worked like a charm. Awesome Post.
NOTE: for those it is not working, Put the Content Editor WebPart below the list, it will work.

Thanks for sharing.

Amy T said...

Mike - I'm not a developer and I'm having trouble getting this to work.

I am trying to color-code a single cell based on a value of that cell but I can't even get the coloring to work on an entire row (parentNode).... There is no javascript error shown.

I posted your exact script then changed two values to match my data (Major and/or Disabling). This did not work.

I changed one line (Major) to say Major contained in the cell and it's still not coloring anything.

Here is the partial code I used. Any ideas??

thank you!!


if (x[i].innerHTML.indexOf("Major") == 0)


{
x[i].parentNode.style.backgroundColor='yellow';
}

if (x[i].innerHTML=="Disabling")
{
x[i].parentNode.style.backgroundColor='orange'; }

Mike Smith said...

Amy T,

You sample code looks ok. Just be aware that JavaScript is case sensitive and your sample will only match "Major" and not "major" or "MAJOR".

Are you working in SharePoint 2007 or 2010? The code is the same for both, but the Content Editor Web Part is different. (My book covers the details for both.)

First, test this with a sample task list, just to make sure it works for you.

Second, make sure the Content Editor Web Part has been moved below the list web part.

Mike

Doug Mayes said...

Great script! I got it to work as is. The next step for me is I want to change what it looks for to highlight the row. Instead of status I want to compare a date in a column named Handoff-P with todays date and if it is greater than 15 business days difference no color, 14 - 10 business days difference the row color is yellow and 9 or less business days difference the row color is red

So if the date in Handoff-P is 10/12/11 the row would be yellow based on todays date of 9/26/11 (12 business days difference)

Mike Smith said...

Doug,

This is similar to what you are looking for:
http://techtrainingnotes.blogspot.com/2009/03/sharepoint-past-due-late-tasks-in-task.html

Mike

Lindsay said...

Mike Smith you are a genius! Who needs IT when you can offer such brilliant business friendly solutions!

Anonymous said...

Mike, this works very well for custom list.But when I tried to do for external list it didnot work.Please guide me how to do for external list. Thanks for the great post.

Mike Smith said...

Anonymous,

As much as Microsoft tried to make external lists behave as normal lists, they are a bit "different". I'll add this to my todo list... so check back.

Mike

Roger M. said...

Just ordered your book...the preview on Amazon looks great. Does your book talk about color coding based on things like positive or negative values (i.e., if value < 0 make it red)
Can't wait till the book gets here.

Mike Smith said...

Roger,

Yes it does in general. Take a look at color coding past due tasks. Let me know if you need a specific example.

Thanks for ordering the book!

Mike

Roger M. said...

Can you post a snippet of code that shows how to apply color to a particular column - the entire column (i.e., column 7). I see the 'past due' blog, but I'm having trouble translating that past due date column logic to a regular number or text field.
Thanks...the book is great by the way!

Mike Smith said...

Roger,

Are you just wanting to change the color of a column, or change the color of a column based on a value in one of the fields?

Mike

Roger M. said...

At this point, I just need help changing the color of a column (no checking for values).

I think that will also answer the other questions I have.

Thanks!

Mike Smith said...

Robert,

Here ya go...

http://techtrainingnotes.blogspot.com/2011/12/sharepoint-change-color-of-web-part.html

Mike

Anonymous said...

Hey Mike,

I've used the code and it worked great to color code some cells in my list, but the colours only apply on the default view and not any other list views that i have created.

is there any way to remedy this?

Thanks,

Andrew

Mike Smith said...

Andrew,

Each view is a separate ASPX page and each will need to have the customization.

Mike

Lionel said...

This worked great for me. So i ordered the book a few days ago. Can't wait to receive it!

Mike Smith said...

Thanks!

Mike

Anonymous said...

Great Stuff!!!! Thanks

Ihmunro said...

Hi There

I was using this on an older version of Sharepoint and it works well.

I am now using SP 2010 but am having problems getting it to work.

Is there anything I should change ? or does it not work in SP 2010 ?

Iain

Mike Smith said...

Ihmunro,

The code works just fine with SP 2010, and SharePoint Online/365. The problem may be with the Content Editor Web Part.

Add the JavaScript to a text file, upload the file to a library, add a Content Editor Web Part and add the URL to the text file to the Content Link box.

Also see here: http://techtrainingnotes.blogspot.com/2012/02/sharepoint-how-to-add-javascript-to.html

> am having problems getting it to work

Any errors? What's happening?

Mike

Anonymous said...

Thanks for the code.. It works great! How can I modify it to look for values in a specific column and not the whole page? e.g. I want to look for "Completed" in the "Status" column.

I'm thinking that, just in case I use the same word ("Completed") somewhere else in the doc.

Thanks

Mike Smith said...

> How can I modify it to look for values in a specific column and not the whole page?

You can add an "if" to check to see if you are checking the desired column. Something like this:

if (x[i].innerHTML=="Completed" && x[i].cellIndex==5)
{
x[i].parentNode.style.backgroundColor='lightblue'; // set the color
}

The "cellIndex" is used to make sure we have found the correct column. When counting columns remember the first column is "0" and to count the checkmark and attachments columns.

Mike

Anonymous said...

Mike,
In your first example the script changes the entire row's background color but does not change the font color. In the second example it changes both the background and font colors but only for a single cell. I want to do example 1 (change the background color of the entire row) but also change the font color for the entire row as well. How do you do that?
Thanks... Mike

Mike Smith said...

Mike,

Just add the line to set the color to each section:

x[i].style.backgroundColor='darkblue'; // set the background color
x[i].style.color='white'; //set the font color

Mike

Kasey Pickar said...

This is all pretty much plagarized but this thread was extremely helpful for me to put it all together..thanks all!! Also, not sure if this is going to look correct but here goes...All together now...

** The DIV and NOBR []'s will need to be changed to <>'


var x = document.getElementsByTagName("TD") // find all of the TDs
var i=0;
for (i=0;i<x.length;i++)
{
if (x[i].className=="ms-vb2") //find the TDs styled for lists
{

// FOR GENERAL FIELDS
if (x[i].innerHTML=="") //find the data to use to determine the color
{
x[i].style.backgroundColor='yellow'; // set the background color
x[i].style.color='black'; //set the font color
}

// FOR NUMBERS
if (x[i].innerHTML.toUpperCase()=="[DIV ALIGN=RIGHT][/DIV]") //find the data to use to determine the color
{
// BACKGROUND FOR THE ENTIRE ROW x[i].parentNode.style.backgroundColor='yellow'; // set the background color
// TEXT FOR THE ENTIRE ROW x[i].parentNode.style.Color.color='black'; //set the font color
x[i].style.backgroundColor='yellow'; // set the background color
x[i].style.Color.color='black'; //set the font color
}

// FOR DATES
if (x[i].innerHTML.toUpperCase()=="[NOBR][/NOBR]") //find the data to use to determine the color
{
// TO HIGHLIGHT THE WHOLE ROW x[i].parentNode.style.backgroundColor='yellow'; // set the background color
// TO HIGHLIGHT THE WHOLE ROW x[i].parentNode.style.Color.color='black'; //set the font color
x[i].style.backgroundColor='yellow'; // set the background color
x[i].style.Color.color='black'; //set the font color
}
} }

Maria said...

Hi Mike,
I'm trying to make a drop down list field called 'Rag' change colour depending on the choice, so I used this code to try and change it to Red, but can see the code in the web part and no change to the field. Can you see what I have done wrong?

if (Rag[i].className==”ms-vb2”) //find the TDs styled for lists
{
if (Rag[i].innerHTML==”Red”) //find the data to use to determine the color
{
x[i].style.backgroundColor='red'; // set the background color
x[i].style.color='red'; //set the font color
}
}

Mike Smith said...

Maria,

The code in the article should work as is. I.e. use:

if (x[i].className==”ms-vb2”) { if (x[i].innerHTML==”Red”)

instead of:

if (Rag[i].className==”ms-vb2”){ if (Rag[i].innerHTML==”Red”)

"Rag[i]" does not mean anyting unless you have created a JavaScript array named Rag.

Mike

Dan said...

Hi Mike,

As many people have said THANK YOU!! This is great. One question, I am looking at using this on some other lists also but I am not a coder by any means and was wondering if you could explin how to change to column it looks? I.e. If I wanted to change it from looking up the "Status" column to "Priority" column

Thanks

Mike Smith said...

Dan,

The code above will still work for you. It does not look at any column, it just looks at the data. I.e. it looks for a cell with "In Progress" and makes it lightgreen.

To color code by priority just look for "(1) High" (or what ever values you have in that column) instead of "In Progress".

Mike

Dan Hipkin said...

Perfect! Thanks again Mike, cracking post

Anonymous said...

Worked like a charm! Thank you!

Dan said...

Hi Mike,

I just thought I would share my solution to grouped lists issue that had previously been mentioned.

I found some javascript that collapses expanded groups in a list on page load that sits in a web part. So if you group a list and set the default to expanded and use your colour CEWP then that will apply to the cells/row and then the javascript will collapse the groups leaving the coloured cell/row in place

I have set this up on several sites and it works perfectly :)

Not sure if you allow external links on your blog posts but this is where I found the group collapse code: http://spyralout.com/tag/collapse-all-groups-sharepoint-list/

Hope this helps

Mike Smith said...

Dan,

> Not sure if you allow external links on your blog posts

By all means! (as long as it adds value to the post)

Thanks for the link.

Mike

Anonymous said...

I am glad to have found your blog. However, as I novice I can't seem to get it to work. In looking at your post can you expand on what values need to be changed in your java script.

For example your script:
if (x[i].className==”ms-vb2”) { if (x[i].innerHTML==”Red”)

do I have to define what x[i] is?
what about TD tags?

Mike Smith said...

Anonymous,

You should not have to change the code at all as it is simply looking for any list with a cell containing a keyword like "Not Started".

Two things to check:
1) The code you posted above has word processing style quotes (”) instead of normal single quotes (') or double quotes (").
2) Make sure the Content Editor Web Part is placed below the list web part you are wanting to impact.

> do I have to define what x[i] is?

No, the "x" is the collection of all of the TD tags found on the page and "x[i]" is one of the TDs that the FOR loop is checking.

Mike

Anonymous said...

Hi Mike - would this work on 1 word within a column of a List? One of my site owners is looking to change the color to red, for RED status, but the word is the first word in a column with more text.

Mike Smith said...

> would this work on 1 word
Yes

Instead of:
if (x[i].innerHTML=="In Progress")

use:
if (x[i].innerHTML.substring(0,3)=="RED")

Note that the "RED" is case sensitive so you might want to use:
if (x[i].innerHTML.toUpperCase().substring(0,3)=="RED")

Mike

Anonymous said...

This is AWESOME! Thank you for sharing!!

Ricky said...

This is an amazingly easier than using DVWP. Thanks a lot for posting this.

Anonymous said...

Hi Mike,

I am working on Sharepoint 2010.
I am using this code to set up a background color in a row that contains "johnson". I have added CEWP below the web part. This is the code

script type="text/javascript" language="javascript">
var x = document.getElementsByTagName("TD") // find all of the TDs
var i=0;
for (i=0;i

What am i missing? Thanks

Martin Krenn said...

Unfortunately it doesn't work if the Phrase that should be colored is a link (e.g. a Worklow-State). It works only if the phrase is pure text. I checked also the class style for the cells and it was also ms-vb2.

Any ideas?

BR
Martin K.

Blake Reader said...

Hi Mike,

Awesome write up, thanks for this! I'm slightly stuck on one very simple area though and I was hoping you maybe able to help me.

What i want to do is set the background colour of a row and also change the text colour. Ive tried looking at both your examples but when i use the javascript line from your 'Row' CEWP code it only changes the text of the target cell as opposed to changing the text for that row.

Are you able to help me add colour to text as well as the row?

Mike Smith said...

Blake,

The problem is that each column type (hyperlink, multiple lines of text, etc.) each have their own nested HTMl and CSS. The following will work with normal text and hyperlink columns to set the text to red.

Add this code in each "if (x[i].innerHTML==" block.


var theRow = x[i].parentNode;
var cells = theRow.getElementsByTagName("TD");
for (k=0;k 0)
{

for (k2=0;k2<Atags.length;k2++)
{
Atags[k2].style.color="red";
}
}

}


Mike

Blake Reader said...

Mike,

Thank you very much, being someone who is still trying to get to grips with JQuery/Javascript where would i insert this into my code? In particular I'm using this:

var x = document.getElementsByTagName("TD") // find all of the TDs
var i=0;
for (i=0;i<x.length;i++)
{

if (x[i].className=="ms-vb2") //find the TDs styled for lists
{

if (x[i].innerHTML=="Pending") //find the data to use to determine the color
{
x[i].parentNode.style.backgroundColor='FF0000'; // set the color
}


}

}

So i can set a row as red when its in a 'pending' state (which is done via document approvals) I need the text for that row to be white

I've tried inserting your code in various places but this breaks it, clearly this is my fault not yours so it would be handy if you could correct my error for me.

As always many thanks for your assistance!

Mike Smith said...

Blake,

Add this code in each "if (x[i].innerHTML==" block.

I.e. immediately after this line:

x[i].parentNode.style.backgroundColor='FF0000'; // set the color

Blake Reader said...

Mike,

I've done what you said below:

var x = document.getElementsByTagName("TD") // find all of the TDs
var i=0;
for (i=0;i<x.length;i++)
{

if (x[i].className=="ms-vb2") //find the TDs styled for lists
{

if (x[i].innerHTML=="Pending") //find the data to use to determine the color
{
x[i].parentNode.style.backgroundColor='FF0000'; // set the color
var theRow = x[i].parentNode;
var cells = theRow.getElementsByTagName("TD");
for (k=0;k 0)
{

for (k2=0;k2<Atags.length;k2++)
{
Atags[k2].style.color="white";
}
}

}
}


}

}

The only thing i haven't included is the script tags. This still doesn't work I'm afraid?

So your aware I have 3 columns in my document library, Managed metadata, single line of text and a choice field. (I also have the created by, modified by and checked out to columns)

Can you also let me know somewhere i can make a donation to you for your assistance so far. I have your book and only recently been getting right into some of your stuff and i feel it's only fair to give something back to someone who offers so much for nothing in return!

Mike Smith said...

Blake,

The only problem I see in your code is this one line:

for (k=0;k 0)

Which was probably damaged by the blog editor. In any case, it should look like this:

for (k=0; k < cells.length; k++)

Other things:
- is there any JavaScript error being displayed, or an error icon in the browser's status bar at the bottom?
- did you add the code to a Content Editor Web Part, and is it placed below the list web part?
- have you changed any of the options for the list web part, especially the Async options?
- which version of SharePoint?

Mike

robby economides said...

I am trying to do this in SharePoint 2013 Office 365 Can you give me any incite on how to do this? I just want to make a list that I have show a color if it has a value in it. (ie. In Progress(Yellow), Closed (Red) etc...

I have been trying this for days any help is greatly appreciated.

Robby

Anonymous said...

Hi Mike,

var x = document.getElementsByTagName("TD") // find all of the TDs

How can i find TD of Sttaus Column?

Thanks and Regards,
Santhoshi

Mike Smith said...

Santhoshi,

The code above does not find the Status column, it finds TDs that contain the status values such as "Pending".

If you wanted to work with a particular column, then you would need to find the <TABLE> and then find the rows <TR> and select the "nth column" (nth <TD>). Remember that the first column will be column zero and all columns are counted (including icons, checkboxes etc.)

Mike

Anonymous said...

How do you then slect the specific column to be higlighted and to look for specific words;
i.e my column is called Riska ratings and i want to change all Low - Green, Moderate - Yellow and so on - so only for this column?!

Mike Smith said...

If those words are unique to that column, then just use the code above and have it look for "Low" instead of "In Progress" and display it in green. The JavaScript above does not care which list or column, only that it finds a cell with <td>Low</td>.

If the text could also show up in other columns then you might try something like this: Find all <tr> tags. Then check the Nth column (<td>) to see if it contains "Low".

Mike

Anonymous said...

so in that case, instead of:

var i=0;
for (i=0;i<x.length;i++)
{
if (x[i].className=="ms-vb2") //find the TDs styled for lists
{
if (x[i].innerHTML=="Not Started") //find the data to use to determine the color
{
x[i].parentNode.style.backgroundColor='white'; // set the color
}

it would be:


var i=0;
for (i=0;i<x.length;i++)
{

if (x[i].className=="ms-vb2") //find the TDs styled for lists
{

if (x[i].Risk Ratins=="Low") //find the data to use to determine the color
{
x[i].style.backgroundColor='green'; // set the color
}

i might be wrong in this case - that might be a reason it's not working - im a newbie and any help is greatly appreciated;

and where/how do i add the column number?

yes, I am looking for specific column caled Risk ratings - but hte values are shown all over place too.

ira said...

I'm just going to add on top those two questions; so I do have specific column, which is column called CodeR, and its the 7th column from the beginning - hence i guess it makes it 6th since we count from zero; so my actual question is: what is the code to look for the Column CodeR, 6th Column, for the word Progress, to change to green, N/A to change to Grey and so on - i have these words accross the table so i only want that specific column to higlight - change the colors accordingly....I've been working on this for some time, and I am newbie at this, so any help is greatly appreciated:)
Thanks

Mike Smith said...

As far as picking a single column... there should be an example in my book :-)
In any case, I'll try to get an example posted in the next few days. (I'm almost 24x7 busy right now.)

Mike

ira said...

great, thanks; i ordered the book - should come soon:) thanks

ira said...

Hi Mike, i got your book, and there is not much of explanation on the specific cell coding - if you got the chance to give us some insight on so, it would be great?
thanks,
Ira

ira said...

Hi there,
any news regarding color coding single cell?

Mike Smith said...

ira,

You won't be able to do it with CSS as you are testing against data.

I would need to know which version of SharePoint and what type of web part you are using for exact code, but it would generally like this:

var colNumber = 4; // column to test

var t = document.getElementById("WebPartWPQ3");

for (var i=0; i<t.rows.length; i++)
{
if (t.rows[i].cells[colNumber].innerText=="wordtofind")
{
t.rows[i].cells[colNumber].style.color="red";
}
}


Mike

Anonymous said...

Hi Mike,
I echo the thanks from everyone. The code works fantastic on different views in my main library.
I'd like to use it on a page that has various views available for people and Easy Tabs script for navigation.
I tried adding the CEWP to the web part zone with the code, but it doesn't seem to like it.
I moved below a specific webpart view, below all and below the CEWP with the Easy tab html, but to no avail.

Is there any way to change the code so it works in this scenario?

Thanks!
Jen

Mike Smith said...

Jen,

I've not used Easy Tabs, but looking at it I would guess that it takes each web part (including the CEWP with your code) and hides them, except for the web part in the selected tab. You may need to edit the page in SharePoint Designer and add the JavaScript just before the end tag of the PlaceHolderMain content tag.

Mike

M. Wood said...

Hi Mike,

Your website has been very helpful...Thank you.

I currently have several columns with dates and I'm using the following:
if (Date.parse(x[i].parentNode.childNodes[colDueDate].childNodes[0].innerHTML)<d.getTime() )

However, i'd like this to work for all columns and not just one. Is there an easy way to do this? Perhaps colDueDate could be an array?

Anonymous said...

I am not a developer and this very helpful one and its working with me in my custom list.

I have one question though. How to change the font color? I use the code but it does not work.

x[i].parentNode.style.backgroundColor='lightblue'; // set the color
x[i].parentNode.style.Color='white'; // set the color

even this one is not working too..

x[i].parentNode.style.backgroundColor='lightblue'; // set the color
x[i].style.backgroundColor='lightblue'; // set the color

:: Danny

Mike Smith said...

Danny,

JavaScript is always case sensitive.
Use style.color instead of style.Color.

http://www.w3schools.com/jsref/prop_style_color.asp

Your backgroundColor looks to be correct:
style.backgroundColor='lightblue'

Mike

Note to spammers...

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.