1

How to generate different background colors for list elements automatically?

Here is the static html code what should be displayed with different background-color.

<ul>
    <li>
        <a href=#">I am the first element</a>
    </li>
    <li>
        <a href=#">I am the 2nd element</a>
    </li>
    <li>
        <a href=#">I am the 3rd element</a>
    </li>
</ul>

No chance to add class or style manually, so I think using jQuery is the easiest solution. Here is my first try:

$(document).ready(function() {
    $('.toc > ul > li').each(function(e){
        var n = $(this).children().text().length*222222;
        var h = n.toString(16).substr(0,6);
        $(this).css({'background-color':'#'+h});
        //$(this).append(h);
    });
});

The result is a bit ugly, and there are similar colors what make this script unusable.

Any other idea to make beautiful automatically colorized lists?

eapo
  • 1,053
  • 1
  • 19
  • 40
  • `var n = $(this).children().text().length*222222; var h = n.toString(16).substr(0,6);` Is this supposed to be a random hex code generator? – Sterling Archer Dec 17 '13 at 20:17
  • 2
    Can you provide some information about how you would like them colored? e.g., randomly, alternating, following some pattern (rainbow), etc. – Tom Pietrosanti Dec 17 '13 at 20:17
  • not using random, because trying to use fixed colors, based on content. following some pattern should be great, or using some predefined nice pantone-like colours. – eapo Dec 17 '13 at 20:32

3 Answers3

3

To make thing look good you're going to need to define a set of colours. Random colours will often be awful.

var clr = "000000,22222,44444,66666,88888,a0a0a0".split(",")
$('.toc > ul > li').each(function(){
      $(this).css('background-color',clr[$(this).index()])   
})
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

See this page:

Random color generator in JavaScript

Also using it i have created a fiddle:

http://jsfiddle.net/3exK5/

var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
    color += letters[Math.round(Math.random() * 15)];
}
    $(this).css({'background-color':''+color+''});
Community
  • 1
  • 1
Zword
  • 6,605
  • 3
  • 27
  • 52
0

If you're looking for random colors that look sort of similar(?) you might want to look into using hsl() to define your colors.

You could just do like...

hsl( randomNumberBetween0and360, 100%, 50% );

and get a bunch of colors that looks like they belong with each other.

Here is a quick demo: http://jsbin.com/EKediJU/1/edit?html,js,output

If you need support for IE there's a nice little script called TinyColor that can help.

Bill Criswell
  • 32,161
  • 7
  • 75
  • 66