Auto-colored labels for bootstrap

This article shows hot to create bootstrap labels which are automatically colored.

2 Min. Lesezeit

The Problem

I wanted to use bootstrap labels for visual grouping. That means that labels with the same content should have the same color.

labels.png

This can be done manually, but it is a boring task to come up with new colors every time you ‘invent’ a new label.

The Solution

My approach is that the content of the label is somehow hashed and afterward transformed into a color.

// Converts a String to a color. The more similar strings are,
// the more similar will be the color.
function stringToColour(str) 
{
    var hash = 0;
    for (var i = 0; i < str.length; i++) 
    {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    var colour = '#';
    for (var i = 0; i < 3; i++) 
    {
        var value = (hash >> (i * 8)) & 0xFF;
        colour += ('00' + value.toString(16)).substr(-2);
    }
    return colour;
}

// colorize the labels after tha page has laoded
$( window ).load(function() 
{
  $('.label-autocolor').each(function (index, value) 
  { 
   var color = stringToColour($(value).text());
   $(value).css('background-color', color);
 });
  
});

This works pretty well. Try it out on jsfiddle. Just insert in the upper left box a new label (e.g: <span class="label label-autocolor">Message three</span>) and press the run button. It should appear in a new different colour.

Happy coding !