SOLDIER-OF-FORTUNE
SOLDIER-OF-FORTUNE

Reputation: 1654

style each div with a different color using jquery or javascript

I have a home page with ul li div the div is a square box and i have 3x3 at the top. The bottom section of my site is code generated mark up and i have something similar.

I would like to give each div "box" a color, currently they are all styled with css. Is there a way with jquery to check for ul li div and if the div exists then add a DIFFERENT colour to the inline style? I would need to store the colors in the script.

This is how i could start?:

$("div.box").css({"background-color": "color"});

Here is my example cut down markup:

<ul>
<li data-target="aboutme" data-target-activation="click" style="margin-top:0px" class="tile high me">
          <div>
          <h2>About Me</h2>
        <h3></h3>
         <img width="48" height="48" alt="" class="icon" src="images/icons/x.png">
     </div>
</li>

<li data-target="aboutme" data-target-activation="click" style="margin-top:0px" class="tile high me">
          <div>
          <h2>Pane 2</h2>
        <h3></h3>
         <img width="48" height="48" alt="" class="icon" src="images/icons/x.png">
     </div>
</li>

<li data-target="aboutme" data-target-activation="click" style="margin-top:0px" class="tile high me">
          <div>
          <h2>Pane 3</h2>
        <h3></h3>
         <img width="48" height="48" alt="" class="icon" src="images/icons/x.png">
     </div>
</li>
</ul>

This is the css:

       .tiles {
        height: 95%;
        margin: 0 auto;
        min-height: 950px;
        overflow: visible;
        padding: 10px;
        width: 957px;
    }

    .tile.high {
    float: left;
        height: 200px;
        margin-top: -100px;
        padding-left: 10px;
        width: 23.6%;
    }

    li.tile div {
        background-color: #00ABA9;
    }

    .tile div {
        background-repeat: no-repeat;
        height: 100%;
        margin: 10px 10px 0;
        overflow: hidden;
        width: 100%;

    }

Upvotes: 2

Views: 6203

Answers (2)

galymzhan
galymzhan

Reputation: 5523

Loop through div's and use different color on each:

// Declare colors you want to use
var myColors = [
    '#f00', '#abc', '#123'
];
var i = 0;
$('div.box').each(function() {
    $(this).css('background-color', myColors[i]);
    i = (i + 1) % myColors.length;
});

Check online: http://jsfiddle.net/4NVRQ/

Upvotes: 9

elclanrs
elclanrs

Reputation: 94101

var 

color = function(){
    return '#' + Math.floor(Math.random()*16777215).toString(16);
},
$els = $('div.box'),
colorify = function(els){
    els.each(function(){
        $(this).css('backgroundColor', color());
    });
};

colorify($els);

Upvotes: 1

Related Questions