<html>
<head>
<title> Colors </title>
</head>
<body>
<script type="text/javascript">
var a = parseInt(prompt("Enter R"));
var b = parseInt(prompt("Enter G"));
var c = parseInt(prompt("Enter B"));
document.body.style.backgroundColor=rgb(a,b,c);
</script>
</body>
</html>
Why doesn’t the background color change according to the RGB values? What have I done wrong??
You need to use quotes:
JS Fiddle demo.
Or:
JS Fiddle demo.
Unquoted the JavaScript is passing the variables, as arguments,
a,bandcto an undefined function calledrgb(). As you’re setting a CSS property you need to pass a string, hence the requirement of quoting.Oh, and also you’re using
parseInt()which doesn’t require a radix to be passed in, but it’s better (and easier to avoid problems) if you do (the radix being the expected number-base):JS Fiddle demo (In the demo I use
105just so it’s clear the default is being used if the cancel button is used).And if someone hits ‘cancel’ on the prompt, you might want to supply a default argument to ensure that an actual colour-value is passed, since cancel otherwise, I think, evaluates to
false(I’m assuming you’d prefer255, but obviously adjust to taste).You could also, of course, simply define a function:
JS Fiddle demo
And this approach has the (perhaps specious) benefit of allowing a custom default value to be used:
JS Fiddle demo
References:
||(logicalOR) operator.Array.join().Element.style.parseInt().