Question

I'm trying to implement a very simple JavaScript program: every time you click the button, the RGB values of the background color are randomized.

Here's the Javascript:

function change() {
    var x = Math.floor(Math.random() * 256); // range is 0-255
    var y = Math.floor(Math.random() * 256);
    var z = Math.floor(Math.random() * 256);
    var thergb = "'rgb(" + x + "," + y + "," + z + ")'"; 
    console.log(thergb);
    document.body.style.background=thergb;
}

I'm pretty sure the problem is in how I hack together the thergb variable, but there are no errors in the console so I'm not quite sure. I log the console just to make sure it's giving me an actual random rgb, which it is.

Here's the full JSFiddle: http://jsfiddle.net/L92bY/

Was it helpful?

Solution

You have wrapped it in ' .. why ?

If you remove that it works..

var thergb = "rgb(" + x + "," + y + "," + z + ")"; 

Demo at http://jsfiddle.net/gaby/L92bY/9/

(you also needed to define the change function in the head tag and not in the onLoad event..)

OTHER TIPS

The CSS syntax for an rgb() value does not include single quotes.

Change 'rgb(x,y,z)' to rgb(x,y,z).

Two things:

  1. You need to choose one of the "nowrap" options for where the fiddle server puts your code.
  2. You need to get rid of the single-quote characters around your "rgb()" expression.

        var thergb = "rgb(" + x + "," + y + "," + z + ")"; 
    

Personally I'd set "backgroundColor" instead of just "background", but it works (in Firefox at least) to set "background".

Fixed fiddle.

Working fiddle (just corrected your code): http://jsfiddle.net/L92bY/18/

The syntax for the CSS color as rgb is rgb(r,g,b) (no extra apostrophe "'") = not 'rgb(r,g,b)'

function change() {
    var x = Math.floor(Math.random() * 256); // range is 0-255
    var y = Math.floor(Math.random() * 256);
    var z = Math.floor(Math.random() * 256);
    var thergb = "rgb(" + x + "," + y + "," + z + ")"; 
    console.log(thergb);
    document.body.style.background=thergb;
}

PS: If this is not working for you you are calling this javascript function BEFORE it was declared.

You could probably also just simplify where your code went wrong by using string template literals.

var thergb = `rgb(${x}, ${y}, ${z})`
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top