How to change the row color of a View based on taxonomy id?

| | 2 min read

There might be a scenario in a Drupal website where you find that you need to change the color of a row in a View based on the taxonomy id. If you have encountered such a scenario then read on to find out the solution.

Follow the steps below to change the row color based on Taxonomy id.

  • Install and activate Colorfield module: http://drupal.org/project/color_field
  • Add a color field named "color" to the taxonomy entity. (Taxonomy->manage fields)
  • Determine the colors for your terms by editing them.
  • Next, inside your view, add a relationship "Content: Taxonomy terms on node"
  • Next add taxonomy:color as a field, and exclude it from display.
  • After that inn views format, select table settings, add "color-[field_color]" for the "Row class".
  • Add a "Global text field" to the header of the view.
  • Choose "Text Format" as "Fully HTML" and paste the JS code below into text area (just remember to change YOUR-VIEW-CLASS to your view's class):
    
<script type="text/javascript">
  (function ($) {
  $(document).ready(function() {
    $(".YOUR-VIEW-CLASS tbody tr").each(function() {
      if (this.className.match(/(?:^|\s)color-(.*?)(?:$|\s)\b/) !== null) {
        var myColor = this.className.match(/(?:^|\s)color-(.*?)(?:$|\s)\b/)[1];
        $(this).css("background", "#" + myColor);
      }
    });
  });

  $(document).ajaxComplete(function() {
    $(".YOUR-VIEW-CLASS tbody tr").each(function() {
      if (this.className.match(/(?:^|\s)color-(.*?)(?:$|\s)\b/) !== null) {
        var myColor = this.className.match(/(?:^|\s)color-(.*?)(?:$|\s)\b/)[1];
        $(this).css("background", "#" + myColor);
      }
    });
  });
})(jQuery);
</script>

Hope that helps.

The easiest way to solve a Drupal issue is to hand it to the Drupal experts. Do you need professional help in building your Drupal site? We can provide a wide range of Drupal services to help you deploy your Drupal site easily and quickly. Get in touch with us to know more.