[Solved] Random BG Colors for DIV

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
techkid
Forum Commoner
Posts: 54
Joined: Sat Sep 05, 2009 11:18 pm
Location: Maldives

[Solved] Random BG Colors for DIV

Post by techkid »

I want to give the div random background colors every time the page loads, and I want to specify those colors as well. Anyone has an idea?

I don't want the same color to appear on the same div every time.

Suppose I want 3 colors, and I have 3 div classes. How can I do it? I found few jQuery codes which can do the function, but the problem is, the same color appears on the same div when the page is reloaded.
Last edited by techkid on Fri Jan 27, 2012 12:52 pm, edited 1 time in total.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Random BG Colors for DIV

Post by Celauran »

Show us the code you're using and we'll see what we can do from there.
User avatar
techkid
Forum Commoner
Posts: 54
Joined: Sat Sep 05, 2009 11:18 pm
Location: Maldives

Re: Random BG Colors for DIV

Post by techkid »

Here's what I have used so far. The issue with this is, all the div element has same color, Instead I want to display different colors.

Code: Select all

<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.min.js"></script>
</head>
<body>
  <div class="controls-wrapper">some text</div>
  <div class="controls-wrapper">some text</div>
  <div class="controls-wrapper">some text</div>
  <div class="controls-wrapper">some text</div>
  <div class="controls-wrapper">some text</div>
</body>
<script>
$(document).ready(function(){
  var colors = ["#CCCCCC","#333333","#990099"];                
  var rand = Math.floor(Math.random()*colors.length);           
  $('.controls-wrapper').css("background-color", colors[rand]);
});
</script>
</html>
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Random BG Colors for DIV

Post by Celauran »

Code: Select all

$(document).ready(function(){
    var colors = ["#CCCCCC","#333333","#990099"];
    $('.controls-wrapper').each(function() {
        var rand = Math.floor(Math.random()*colors.length);
        $(this).css("background-color", colors[rand]);
    });
});
User avatar
techkid
Forum Commoner
Posts: 54
Joined: Sat Sep 05, 2009 11:18 pm
Location: Maldives

Re: Random BG Colors for DIV

Post by techkid »

Thanks, works well.
Post Reply