1

Possible Duplicate:
Apply different background color using jquery

I have three divs on a page all with the class .contact-image

I am looking to have these three divs have different background colours (cyan, yellow, magenta)- ideally rgb colors with a transparency of 50%. They don't need to be randomly selected - having as follows is fine. One(Magenta) Two(Cyan) Three(Yellow)

I am a novice to JQuery and so far have got this code from an answer on here to a slightly similar question.

$(function() {
$(".contact-image").each(function() {
    var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
     $(this).css("background-color", hue);
});

});

This colors all 3 divs a different colour randomly but I don't have the knowledge to adjust this to my needs. Any help will be very much appreciated..

Community
  • 1
  • 1
lsloss
  • 45
  • 8

3 Answers3

6

You can use the function setter syntax:

$(".contact-image").css("background-color", function(i) {
  return ["magenta", "cyan", "yellow"][i];  // one of the three
});
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • Thank you so much for this pimvdb! What a legend, this is exactly the result I wanted. Thanks everyone else for your answers. – lsloss Jan 18 '13 at 16:43
0
$(function() {
    var colors = ['magenta', 'cyan', 'yellow'];
    $(".contact-image").each(function(i) {
        $(this).css("background-color", colors[i]);
    })
});
  • This is technically better performance-wise as it won't create a new array for each iteration. – Fabrício Matté Jan 18 '13 at 16:32
  • @PaulKarabilo I think that `.each` only works that way with an array, not with an object selection: http://api.jquery.com/jQuery.each/ – paul Jan 18 '13 at 16:32
  • 2
    @paul [jQuery.each](http://api.jquery.com/jQuery.each/) is a generic iteration function; [jQuery.fn.each](http://api.jquery.com/each/) (aka `$().each`, the one being used here) iterates over the elements contained inside a jQuery object. – Fabrício Matté Jan 18 '13 at 16:33
0

One way to do it so that you can set the colors via hex values in the divs themselves:

HTML:

<div class="contact-image" data-color="ffffff">
  Content 1
</div>
<div class="contact-image" data-color="ff0000">
  Content 2
</div>
<div class="contact-image" data-color="000000">
  Content 3
</div>

JQuery:

$(function() {
  $(".contact-image").each(function() {
      var hue = "#"+$(this).data('color');
       $(this).css("background-color", hue);
  });
});
Samsquanch
  • 8,866
  • 12
  • 50
  • 89