I am trying to make it so my websites background changes colour randomly every few seconds. I can get it to change to a random colour but how do I make it loop?
<script type="text/javascript">
$(document).ready(function() {
var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
function colourSet(){
$("body").animate({ backgroundColor: hue}, 2000);
}
colourSet();
});
</script>
You can make it loop simply by having the function register itself as its own completion handler:
NB: the hue has to be picked inside the function otherwise it’ll remain the same colour every time.
Just for fun, you can also make the hue code slightly shorter using some Javascript hacks (ahem):
which takes advantage of two uses of the bitwise
~(“not”) operator to convert floating point to integer, and also because concatenating an array to a string automatically does a.toString()on the array – resulting in a comma separated list.