June 7, 2012

SharePoint: Web part title bar colors using jQuery, part 2


How to set web part title bar colors so that different web parts have different colors? How about making it easy also for content editors who have no HTML/JavaScript/jQuery skills?


Sure thing. Instead of hard coding the colors to web part titles, let’s append name of the color in front of the web part title. Then with jQuery, let’s set the color accordingly, and finally remove the color definition when the page has been rendered.

  1. First, create web part with title [PURPLE]Actual title.
    1. [PURPLE] is the name of the color you want this web part’s title bar to have
  2. Add CEWP to your page, or by other means register the following JavaScript on your page. CEWP must be located after the web parts that are modified as I don’t want to use document.ready as users might notice old colors for a moment when pages reload before the JavaScript kicks in.


    $('td[title^="["]').each(function ()
        $("#" + $(this).attr('id').replace('Title', 'Caption')).prev().html(function (index, oldhtml)
            return oldhtml.substr(oldhtml.indexOf(']') + 1);

jQuery starts with selector is used (^=) to search for web part titles with color definitions. The color is set with background-color in a CSS class, which in this example is WPTITLEPURPLE. Last part of the jQuery above removes the color definition text from the web part titles.

As you might guess, further improvement on this would be to define the color in the web part title using actual colors, e.g., [#CCCCCC], [rgb(123,123,123)], or even with actual names of the colors, like [blue]. One could then use RegExp to get the real color and inject that to correct elements using jQuery. Downside of this is that branding might be adversely affected as any color could be used; also some content editors might not be familiar with these types of color notations.

See part 1 if your web parts and titles are relatively static or content editors like to work with jQuery.


Technorati Tags: ,

No comments:

Post a Comment