Running this code in browser, if no colour is entered, ‘green'(undefined) is rendered.
Random/garbage value leads to black background…
…not selecting or transparent gives white(null)
<HTML>
<HEAD>
<TITLE>Document Object Demo</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=Javascript>
var sAnswer = window.prompt("Please enter your favourite color : choose from the following Yellow, Green, Red, Blue, Pink, Orange, Black, Gray")
document.bgColor = sAnswer
document. write ("<H1>Welcome " + sAnswer + ":-)!!</H1><HR>We are very happy to demonstrate the usage of <I> document. write</I>. Do remember to view the source!<P>")
</SCRIPT>
</BODY>
</HTML>
I use IE9…!
Why is this happening?
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.
OR keep asking the question until a valid answer is given.. (fairly evil imo)
Code not tested but fairly confident it should work :p
Edit, how does it get to the colour green?
In short,
undefinedis typecasted to a string which can be used to set thebgColorproperty, which in turn is parsed and interpreted as a color, making invalid hex characters count for0. Read this for a more in depth explanation.Internet Explorer used this interpretation and the other browsers followed so to not break backwards compatibility.