1

I am trying to change the body background-color to a random color on a button click.

<script>
$( document ).ready(function() {
    $('.SpecButton').click(function() {
        $('body').css('background-color',"<?php 
            $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
            $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
            echo $color;
                ?>");
            });
        });     
</script>

The problem is the first click changes background color, but the second try Does not.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
Mehmet Eren Yener
  • 2,006
  • 1
  • 23
  • 37

2 Answers2

2

You should do the random number generation within javascript. Since PHP code is server side it will only set the random number once, whereas with javascript you can get new random numbers each time the button is clicked.

$( document ).ready(function() {
    $('.SpecButton').click(function() {
        var color = '#'+Math.floor(Math.random()*16777215).toString(16);
        $('body').css('background-color', color );
    });
});     

Fiddle here: http://jsfiddle.net/TQ3hV/

Or if you are ok with RGB colors, this method is probably easiest and cleanest to understand:

var color = 'rgb(' + Math.floor(Math.random() * 255) + ',' 
                   + Math.floor(Math.random() * 255) + ','
                   + Math.floor(Math.random() * 255) + ')';

Fiddle here: http://jsfiddle.net/TQ3hV/1/

Source of random color generators: http://www.paulirish.com/2009/random-hex-color-code-snippets/

Andrew L
  • 1,164
  • 12
  • 20
1

I had the same problem you were having when I tried your code. I didn't like the PHP in there anyway so I found some Javascript for you. Assuming you're loading jquery ahead of the script, I'd skip the inline php and go with something like this:

$( document ).ready(function() {
    $('.SpecButton').click(function() {
        var x = Math.round(0xffffff * Math.random()).toString(16);
        var y = (6-x.length);
        var z = '000000';
        var z1 = z.substring(0,y);
        var color = '#' + z1 + x;
        console.log(color);  // just in case you like the color, here's the number
        $('body').css('background-color', color );
    });
});

I found it in the comments section on this page:

http://css-tricks.com/snippets/javascript/random-hex-color/

charliemagee
  • 683
  • 5
  • 19