You are having this problem because the browser will try to parse something out of w/e you set the bgColor to...
Now your Javascript is fairly questionable, and I can not think of a reason you'd want to do this, but your code should probably look more like this.
(function () {
// Prompts the user to give an answer, this prevents further code execution
var sAnswer = window.prompt("Please enter your favourite color : choose from the following Yellow, Green, Red, Blue, Pink, Orange, Black, Gray");
// Takes care of all falsy valuyes, 0, null, undefined, false
// Ideally some more validation on the input should be done
if(sAnswer) {
document.body.style.backgroundColor = sAnswer;
document.write ("<h1>Welcome " + sAnswer + ":-)!!</h1><hr><p>We are very happy to demonstrate the usage of <i> document. write</i>. Do remember to view the source!</p>");
} else {
document.write ("<p>You did not fill in a valid answer! Refresh.</p>");
}
}());
OR keep asking the question until a valid answer is given.. (fairly evil imo)
(function () {
var sAnswer;
do {
sAnswer = window.prompt("Please enter your favourite color : choose from the following Yellow, Green, Red, Blue, Pink, Orange, Black, Gray")
} while ( !sAnswer );
document.body.style.backgroundColor = sAnswer;
document.write ("<h1>Welcome " + sAnswer + ":-)!!</h1><hr><p>We are very happy to demonstrate the usage of <i> document. write</i>. Do remember to view the source!</p>");
}());
Code not tested but fairly confident it should work :p
Edit, how does it get to the colour green?
In short, undefined
is typecasted to a string which can be used to set the bgColor
property, which in turn is parsed and interpreted as a color, making invalid hex characters count for 0
. Read this for a more in depth explanation.
Internet Explorer used this interpretation and the other browsers followed so to not break backwards compatibility.