'Random Background Color Change
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.
Solution 1:[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:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | charliemagee |
