p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Beginning JavaScript 4th Edition (http://p2p.wrox.com/forumdisplay.php?f=529)
-   -   1st Chapter Example 2 (http://p2p.wrox.com/showthread.php?t=84505)

Ashu2912 July 27th, 2011 01:02 PM

1st Chapter Example 2
 
It is mentioned that the program is interpreted from top to bottom. However, there is some odd behaviour given by the code below :-

Code:

<html>
<head>
<title> Title 1 </title>
</head>
<body>
HI!!!!
</body>
<script type = "text/javascript">
  alert ("Hi!!!");
  document.bgColor = "RED";
</script>
<head>
<title> Title 2 </title>
</head>
<body bgcolor = "YELLOW">
Hi!!! Again
</body>
<head>
<title> TITLE 2 </title>
</head>
</html>

I have mentioned the background colour to be yellow later in the program, but the webpage is being created red in colour, as mentioned in the <script>-</script> block!
Thanks! [:)]

jmcpeak July 27th, 2011 04:32 PM

Howdy, Ashu2912.

You're seeing this behavior because of the markup. According to the HTML specification, an HTML document should have only one head element and one body element. Since you have two body elements, the browser uses the first body element and ignores the second element (but not it's content--in fact, the second element's content is appended to the first body). Because the second body element is ignored, the document's background doesn't change to yellow.

The same behavior is exhibited in the title elements. Your document has three head elements with three title elements. The browser uses the first title element and ignores the second and third.

To give you an idea of what the book was meaning, use this code:

Code:

<html>
<head>
    <title>Title 1</title>
</head>
<body>
<script>
    document.bgColor = "red";
    document.bgColor = "yellow";
</script>
</body>
</html>



All times are GMT -4. The time now is 03:39 AM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.