0

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>

3 Answers 3

5

You can make it loop simply by having the function register itself as its own completion handler:

function colourSet() {
   var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; 
   $("body").animate({ backgroundColor: hue}, 2000, colourSet);
} 

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):

function r() { return ~~(256 * Math.random()) };
function colourSet() {
   var hue = 'rgb(' + [r(), r(), r()] + ')';
   $("body").animate({ backgroundColor: hue}, 2000, colourSet);
}  

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Try using setInterval. See below,

$(document).ready(function() {

    setInterval(function () {
       var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';  
       colourSet(hue);
    }, 30000); //30 seconds

    function colourSet(hue){
       $("body").animate({ backgroundColor: hue}, 2000);
    }   
});

Comments

1

Use setInterval function

<script type="text/javascript">
$(document).ready(function() {

    setInterval(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();
    },60000 /* 60 seconds */);
});
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.