Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Random Background Color

Hello all, could someone please help me here? I have a div called

<div class="posts">

and part of the css is

#posts:before {
content: "";
position: absolute;
background-color: #39ADD1;
}

Now I would like to get the background colour to change randomly every time the page is loaded, but it will only load certain colours (specified beforehand).

How would I do this?

Regards

5 Answers

My apologizes I thought you requested complete random colors. Here is your answer without having to rely on jQuery . Pure raw JavaScript and nothing more:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf=8">
        <style type="text/css">
            #posts {
                width: 90%;
                height: 700px;
                margin: auto
            }
        </style>
    </head>
    <body onload="return ran_col()">
        <div id="posts">
        </div>
        <script type="text/javascript">
            function ran_col() { //function name
                var color = '#'; // hexadecimal starting symbol
                var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0']; //Set your colors here
                color += letters[Math.floor(Math.random() * letters.length)];
                document.getElementById('posts').style.background = color; // Setting the random color on your div element.
            }
        </script>
    </body>
</html>

That is even better. Thanks for the help :)

Anytime, happy to help. Cheers!

Good implementation. Over the past few weeks I've been using Jquery, I'm quite use to it. Nice work. Raw Javascript is the way to go.

Sorry one more question! How can I get it to add the same background colour to more than one div. So #post and #blog? - Thanks

I believe you'd have to target that div just like what was done in Armins code with the post div.

 document.getElementById('blog').style.background = color; // Setting the random color on your div element.

They both should display the same colors.

Perfect that worked like charm on CodePen. Thank you for the help the both of you.

Yup Guled A is correct. Here is a sample:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf=8">
        <style type="text/css">
            #post, #blog {
                width: 45%;
                height: 400px;
                margin: 0 20px;
                float: left;
            }
            #blog {
                float: right;
            }
        </style>
    </head>
    <body onload="return ran_col()">
        <div id="post">
        </div>
        <div id="blog">
        </div>
        <script type="text/javascript">
            function ran_col() { //function name
                var color = '#'; // hexadecimal starting symbol
                var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0']; //Set your colors here
                color += letters[Math.floor(Math.random() * letters.length)];
                document.getElementById('post').style.background = color; // Setting the random color on your div element.
                document.getElementById('blog').style.background = color; // Setting the random color on your div element.
            }
        </script>
    </body>
</html>

Sorry guys, I need some more help? It won't work!

Okay so here is my whole code for the header of my Wordpress site?

<?php
/**
 * The template for Library Header.
 *
 * @package Simon WP Framework
 * @since Simon WP Framework 1.0
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>><head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<?php if (is_search()) { ?>
<meta name="robots" content="noindex, nofollow" />
<?php } ?>
<title>
<?php bloginfo('name'); ?>
<?php wp_title('|'); ?>
</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_url'); ?>/normalize.css" />
<link rel="stylesheet" type="text/css" media="all" href="<?php echo get_stylesheet_uri(); ?>" />

<!-------------------------------------------- Library Header CSS files ------------------------------------------>
  <link rel='stylesheet' media='screen and (max-width: 499px)' href='<?php bloginfo('template_url'); ?>/headers/library/css/499.css' />
  <link rel='stylesheet' media='screen and (min-width: 500px) and (max-width: 799px)' href='<?php bloginfo('template_url'); ?>/headers/library/css/500.css' />
  <link rel='stylesheet' media='screen and (min-width: 800px) and (max-width: 1023px)' href='<?php bloginfo('template_url'); ?>/headers/library/css/800.css' />
  <link rel='stylesheet' media='screen and (min-width: 1024px) and (max-width: 1279px)' href='<?php bloginfo('template_url'); ?>/headers/library/css/1024.css' />
  <link rel='stylesheet' media='screen and (min-width: 1280px) and (max-width: 1365px)' href='<?php bloginfo('template_url'); ?>/headers/library/css/1280.css' />
  <link rel='stylesheet' media='screen and (min-width: 1366px) and (max-width: 1955px)' href='<?php bloginfo('template_url'); ?>/headers/library/css/1366.css' />
  <link rel='stylesheet' media='screen and (min-width: 1600px) and (max-width: 1919px)' href='<?php bloginfo('template_url'); ?>/headers/library/css/1600.css' />
  <link rel='stylesheet' media='screen and (min-width: 1920px)' href='<?php bloginfo('template_url'); ?>/headers/library/css/1920.css' />
<?php include(TEMPLATEPATH . '/inc/fonts/font.php'); ?>
<!-- END -->
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php if ( is_singular() ) wp_enqueue_script( 'comment-reply' ); ?>
<?php wp_enqueue_script("jquery"); ?>
<?php wp_head(); ?>
<script src="<?php bloginfo('template_url'); ?>/menu.js"></script>
<script type="text/javascript">var templateDir = "<?php bloginfo('template_directory') ?>";</script>
<script src="<?php bloginfo('template_url'); ?>/to-top-jquery/to-top-jquery.js"></script>
<script type="text/javascript">
function get_random_color() { //function name
                var color = '#'; // hexadecimal starting symbol
                var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0']; //Set your colors here
                color += letters[Math.floor(Math.random() * letters.length)];
                document.getElementById('posts:before').style.background = color; // Setting the random color on your div element.
                document.getElementByClassName('sidebar').style.background = color; // Setting the random color on your div element.
            }
</script>

<style type="text/css">
#icon
{
    background-image:url('<?php bloginfo('template_url'); ?>/headers/library/images/icons-50px.png');
    }
#icon:hover
{
    background-position:0px -100px;
    cursor:pointer;
}
</style>
</head>
<body onload="return get_random_color()">
<div class="outer_wrap">
  <div class="inner_wrap">
  <!--Header Starts -->
  <div class="sidebar">
  <a href="<?php echo home_url(); ?>" title="<?php bloginfo('name'); ?> Home" id="icon"></a>
  </div>
  </div>
 </div>
``

Sorry for so much code :(

I have used  

```Javascript
document.getElementById('posts:before')

and

document.getElementByClassName('sidemar')

Can I not add a ":" to the ID name and not use "ByClassName" for ".sidebar" What seems to be the problem?

Regards

Aled

I don't think You can use ":before" the way you have it in your code.

document.getElementById('posts:before').style.background = color;

also you are missing the 's' in document.getElementsByClassName. Try something like this:

document.getElementsByClassName('sidebar')[0].style.background = color;

Here is your entire code. I took out all the things that were referencing to other files to make it work locally on mine. Just compare it with yours and start adding in the other lines and see what is causing it to not work.

Here is the working code I made for you:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="" />
<meta name="robots" content="noindex, nofollow" />

<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<style type="text/css">
.sidebar {
    width: 100%;
    height: 500px;
    background-color: red;
}
</style>
<script type="text/javascript">
function ran_col() { //function name
    var color = '#'; // hexadecimal starting symbol
    var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0']; //Set your colors here
    color += letters[Math.floor(Math.random() * letters.length)];

    document.getElementsByClassName('sidebar')[0].style.background = color;
}
</script>
</head>
<body onload="return ran_col()">

  <div class="sidebar">
    <p>test</p>
  </div>
</body>
</html>

I hope this helps.

Caleb Shook
Caleb Shook
2,357 Points

Dude. Sick code.

var swag = "Good Job!"

console.log(swag)

Gareth Gomersall
Gareth Gomersall
2,890 Points

Could some one help me with this? I'm trying to use the following:

window.onload = function(){
  function rand_color() {
    var color = '#';
    var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0'];
    color += letters[Math.floor(Math.random() * letters.length)];
    document.getElementsByClassName('main')[0].style.background = color;
  }
  rand_color();

}

calling it in my html like this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bali Chonk</title>
    <link rel="stylesheet" href="css/style.css">
    <script type="text/javascript" href="js/script.js"></script>

  </head>
  <body class="main">
    <div>
      <h2>Some text to go here for Bali Chonk</h2>
    </div>
  </body>
</html>

but it doesn't seem to work, any help would be greatly appreciated

Hi Aled,

I was not sure if you wanted to use your div with a class or id. In your css it looks like you are calling in id and not a class. So in the mark-up I changed the class to an id.

I would start off by writing a function using JavaScript like this:

function ran_col() { //function name
    var color = '#'; // hexadecimal starting symbol
    var letters = '0123456789ABCDEF'.split(''); //hexadecimal color letters

    //For loop that will create random hexadecimal value.
    for (var i = 0; i < 6; i++) {
        color += letters[Math.round(Math.random() * 15)];
    }

    document.getElementById('posts').style.background = color; // Setting the random color on your div element.
}

On your make up you want to call your JavaScript function "onload" in your body:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf=8">
        <style type="text/css">
            #posts {
                width: 90%;
                height: 700px;
                margin: auto
            }
        </style>
    </head>
    <body onload="return ran_col()">
        <div id="posts">
        </div>
    </body>
</html>

Thanks for replying, but I couldn't see where I would be able to enter a list of colours to use :)

My apologizes I thought you requested complete random colors. Here is your answer without having to rely on jQuery . Pure raw JavaScript and nothing more:

,,,

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf=8"> <style type="text/css"> #posts { width: 90%; height: 700px; margin: auto } </style> </head> <body onload="return get_random_color()"> <div id="posts"> </div> <script type="text/javascript"> function get_random_color() { //function name var color = '#'; // hexadecimal starting symbol var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0']; //Set your colors here color += letters[Math.floor(Math.random() * letters.length)]; document.getElementById('posts').style.background = color; // Setting the random color on your div element. } </script> </body> </html>

,,,

You may need to know Jquery to do this, but I will explain the syntax: First the demo

$(document).ready(function(){

  var colors = ['#e67e22', '#3498db', '#9b59b6', '#e74c3c', '#2c3e50'];

  $('body').css({'background': '' + colors[Math.floor(Math.random() *      colors.length)]});

});

First you make an array with all the colors you want to load when I reload the page.

var colors = ['#e67e22', '#3498db', '#9b59b6', '#e74c3c', '#2c3e50'];

Then you use a method in Jquery to focuses on the elements css attributes specifically the background. I chose the bode element, but you can change it to which ever element you want. The method goes through each of the colors I've specified and puts them on the screen when reloaded randomly.

  $('body').css({'background': '' + colors[Math.floor(Math.random() *      colors.length)]});

For your example. The syntax would look like this.

$(document).ready(function(){

  var colors = ['#e67e22', '#3498db', '#9b59b6', '#e74c3c', '#2c3e50'];

  $('#post').css({'background': '' + colors[Math.floor(Math.random() *      colors.length)]});

});

Thanks for the help, it works perfectly. :)

Hi there,

I've copied and pasted the example above and configured for my use and it now looks like this:

<script type="text/javascript">
    function get_random_color() { //function name
            var color = '#'; // hexadecimal starting symbol
            var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0']; //Set your colors here
            color += letters[Math.floor(Math.random() * letters.length)];
            document.getElementById('header').style.borderBottom = color; // Setting the random color on your div element.
        }
</script>
```html<body onload="return get_random_color()">
</body>

My issue is that whenever the page loads the borderBottom of my header disappears. Does anybody know why this happens and how could i fix it? 

Thanks in advance for your help.