O'Reilly Forums: "Size the Rock" solution isn't working with xhtml - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

"Size the Rock" solution isn't working with xhtml

#1 User is offline   anita 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 42
  • Joined: 06-October 07

Posted 03 January 2008 - 11:52 AM

My "Size the Rock" solution was the same as the file solution with one exception. I used an xhtml doctype declaration. I cut out the declaration and used a plain <html> tag and then the solution worked.

This is what I removed to get the rock to resize.

<xml>
<DOCTYPE>

<html>


Now there is always a chance that my doctype declaration has an error in it. But I did just put it to the validator and it passed.

Here is the whole html page with the xhtml doctype declaration.

<xml>
<DOCTYPE>

<html>

<head>
    <meta>
    <link>
    <title>iRock - The Virtual Pet Rock</title>
    <script>
      var userName;
      
      function resizeRock () {
        document.getElementById("rockImg").style.height = (document.body.clientHeight - 100) * 0.9;
      }
      
      function greetUser() {
        alert('Hello, Iam your pet rock.');
      }
        
      function touchRock () {
        if (userName) {
          alert("I like the attention, " + userName + ". Thank you.");
        }
        
        else {
          userName = prompt("What is you name?", "Enter your name here.");
          if (userName)
            alert("It is good to meet you, " + userName + ".");
        }
        document.getElementById("rockImg").src = "rock_happy.png";
        setTimeout("document.getElementById('rockImg').src = 'rock.png';", 300000);
      }
    </script>
</head>
<body>
    <div>
        <img>
    </div>
</body>
</html>


And the rock stays small.

I'm open for suggestions.

Thanks,
Anita.

As you can see this forum program edits the doctype declaration. So here is the pastie.

http://pastie.caboo.se/134547
0

#2 User is offline   Michael Morrison 

  • Active Member
  • PipPipPipPip
  • Group: O'Reilly Author
  • Posts: 114
  • Joined: 16-October 07
  • Location:Nashville, TN
  • Interests:nerdy tinkering, skateboarding, hockey, pond building, landscaping, architecture/construction

Posted 03 January 2008 - 09:36 PM

Wow, Anita you uncovered a pesky little problem I was unaware of that has to do with how XHTML alters the behavior of browsers. I knew it altered a lot of things associated with HTML but I wasn't aware of it affecting JavaScript to any serious degree. But it does!

What's going on is that the height and width of the body are never getting set because of the way the browser looks at the Web page document differently when in "XHTML" mode. I'm still not entirely certain what the best fix for this problem is, but I do have a fix that works. What you need is to force the window size into the body's width and height so that it can be accessed via document.body.clientWidth and document.body.clientHeight, and get meaningful values. You can do this with a CSS style sheet added to the document that sets the width and height of the body to 100%. It also works better if you set the margin and padding of the body to 0px. Here's the code:

<style type="text/css">
  body, html {
    width:100%;
    height:100%;
    margin:0px;
    padding:0px;
  }
</style>


One other thing that must change in XHTML is that you apparently must always specify units for properties such as the width and height. So when setting the height of the rock in the resizeRock() function, you must add "px" to the new rock height, which also converts the number to a string automatically. Here's the code:

function resizeRock() {
  document.getElementById("rockImg").style.height = (document.body.clientHeight - 100) * 0.9 + "px";
}


We originally debated including DOCTYPEs in all of the code for the book, and ultimately decided that it would distract from the learning since DOCTYPEs are really more of an HTML/XHTML issue. Your problem illuminates the fact that DOCTYPEs also impact JavaScript in some circumstances. I hope this info helps...

-mm
Michael Morrison
Author of Head First JavaScript, Head First PHP & MySQL
0

#3 User is offline   anita 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 42
  • Joined: 06-October 07

Posted 04 January 2008 - 04:29 AM

Thank you for your prompt reply, Michael.

I will try out your coding suggestions and get back to you via the forum with my results.

I certainly can understand your decision to stay away from doctypes with the book since you would have to add subchapters and appendices for every single example.

From my perspective, having the code work in Xhtml 1.0 strict is very important to me since all my information points to the use of that doctype as being best for my personal long term needs.

Perhaps there could be a doctype sticky for the forum and people could post and read quirks specific to their doctype of choice.

It may be a lot of work, or it may be worthwhile if browsers interpret javascript differently for each doctype.

Thank you again, Michael,
Anita.
0

#4 User is offline   anita 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 42
  • Joined: 06-October 07

Posted 06 January 2008 - 05:12 PM

You're either going to love this or hate this. I can't see you being ambivalent.

I tried your recommendations. Well, I do have a separate css file so I used it.

Here is what I experienced.

When I used both body and html as selectors for the same css rule, I couldn't change the top margin for the image. For this I was only in opera.

When I set the html selector for the css rule with both width and height to 100%, the rock increased to the expected size in opera, stayed small in firefox and in safari for windows (beta) and increased to the expected size in internet explorer after I allowed the blocked content.
html {width:100%; height:100%;}


Then I added
*{margin:0px; padding:0px;}
to the top of the css file and the rocks tucked in tighter to the top left in all four browsers.

I had taken out the css rule for the body selector to establish exactly what was doing what earlier so now I replaced it.
body {margin-top:100px; text-align:center;}

All rocks are now front and centre.

Then I added the code:
+ "px"

to the resizeRock function.

Opera and Explorer stayed as they had after the addition of the html rule, which is to say, large. Firefox and Safari for windows have even smaller rocks than before I added the space plus-sign space double quote px double quote code addition. They are now smaller than before.

This may be a bigger obstacle than I had realized.

Not sure what to do now.

Do I forget about it and just learn javascript which I can only use with certain doctypes? Am uncertain.

Thoughts and suggestions welcome,
Anita.

For clarity, here is the pastie.
http://pastie.caboo.se/135935
Both the css file and the html file are on one pastie, css on the top, to save clicking.
0

#5 User is offline   anita 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 42
  • Joined: 06-October 07

Posted 06 January 2008 - 05:28 PM

FYI, I just tried
em
were
px
was in the xhtml file and the rocks all got so big they couldn't fit into the viewport. The opera/explorer rocks where significantly larger than the firefox/safari for windows rocks, though.

A bit like Alice in Wonderland with her 'eat me'/'drink me' problem.

This information probably doesn't lead to a solution, but I thought I'd let you know,
Anita.
0

#6 User is offline   anita 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 42
  • Joined: 06-October 07

Posted 06 January 2008 - 05:58 PM

So now I tried it exactly as you suggested by putting all the css in the html file and it worked.

Here is the pastie:
http://pastie.caboo.se/135964

All four browsers, all big rocks.

So what is going on with the css that it has to be on the same page. Or have I made an error somewhere?

What do you think?

Thanks,
Anita.
0

#7 User is offline   anita 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 42
  • Joined: 06-October 07

Posted 06 January 2008 - 06:54 PM

My fault, my fault. I was styling the wrong css selector.

I was styling body when I should have been styling the div containing the image.

margin-top:100px; text-align:center;
should have been on the div containing the img not the body. I had it on the body. It works now.

Sorry about all the typing traffic.

Here is the pastie. Again both css and xhtml files are on one pastie, css first.

http://pastie.caboo.se/135981

Thanks,
Anita.
0

#8 User is offline   Michael Morrison 

  • Active Member
  • PipPipPipPip
  • Group: O'Reilly Author
  • Posts: 114
  • Joined: 16-October 07
  • Location:Nashville, TN
  • Interests:nerdy tinkering, skateboarding, hockey, pond building, landscaping, architecture/construction

Posted 07 January 2008 - 09:56 AM

No worries. Glad you got it working.

Still a bummer that it required so much experimenting and tweaking just to adhere to standards. In the long run the standards effort will pay off but it certainly does involve some suffering as we continue to move toward it. Just in case you've never been there (although I suspect you have), this Web site is an excellent resource for staying on top of modern browser inconsistencies as they pertain to java script:

http://www.quirksmode.com/

I also highly recommend the PPK on JavaScript book on there as an advanced JavaScript book. It has some really good real world JavaScript advice - but it's definitely for experienced JavaScript programmers.

And just so I don't get in trouble with O'Reilly, since I'm recommending books I can't leave out java script: The Definitive Guide. It really is an awesome reference book for JavaScript.

-mm
Michael Morrison
Author of Head First JavaScript, Head First PHP & MySQL
0

#9 User is offline   anita 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 42
  • Joined: 06-October 07

Posted 07 January 2008 - 12:02 PM

Thanks for the quick reply.

Hadn't been to the recommended link. Am checking it out. Thanks.

Who was the mythical chap who pushed the rock uphill all day. Was it Sisyphus? Seems he's rather a constant companion these days. Oh well, at least I have some company. smile.gif

And thank you for the book recommendations. I will consider them after I finish working through yours.

Thank you, Michael,

Anita.
0

#10 User is offline   Michael Morrison 

  • Active Member
  • PipPipPipPip
  • Group: O'Reilly Author
  • Posts: 114
  • Joined: 16-October 07
  • Location:Nashville, TN
  • Interests:nerdy tinkering, skateboarding, hockey, pond building, landscaping, architecture/construction

Posted 07 January 2008 - 01:06 PM

You're very welcome.

I forgot to mention in my previous reply that "quirks mode" refers to browsers using older, non-standard rendering practices to process and display web page code. When you don't include a DOCTYPE, browsers default to using quirks mode, which is making me regret not going ahead and sticking DOCTYPEs in all of the JavaScript example pages. Fortunately, aside from the iRock I don't think the examples are impacted greatly by quirks mode vs. standards mode.

I'll probably go ahead and add DOCTYPEs to the code as soon as possible and post any other weirdness I encounter, just to be safe. In the meantime, here's a page on the same site I mentioned that does an excellent job of explaining the whole quirks mode/standards mode DOCTYPE issue:

http://www.quirksmode.org/css/quirksmode.html

-mm
Michael Morrison
Author of Head First JavaScript, Head First PHP & MySQL
0

#11 User is offline   anita 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 42
  • Joined: 06-October 07

Posted 07 January 2008 - 01:18 PM

Thanks for the reply, your understanding, and the new link.

Let me know how you want to deal with doctype weirdness, so that I can refer to the material if I encounter any more anomalies.

Thanks,
Anita.
0

#12 User is offline   stephee24 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 28
  • Joined: 08-February 08

Posted 09 February 2008 - 02:06 PM

Yes, yes, yes! Please include doctypes on the files, pretty please! I really don't think it's a good idea to show people samples that are not valid XHTML. I don't think having a doctype will detract from the JS learning.

On that note, the irock examples in Ch03 have mixed case attributes.

<body onLoad="...

0

#13 User is offline   Michael Morrison 

  • Active Member
  • PipPipPipPip
  • Group: O'Reilly Author
  • Posts: 114
  • Joined: 16-October 07
  • Location:Nashville, TN
  • Interests:nerdy tinkering, skateboarding, hockey, pond building, landscaping, architecture/construction

Posted 09 February 2008 - 10:44 PM

(stephee24)
On that note, the irock examples in Ch03 have mixed case attributes.


Are you sure about that? I looked through all of the Chapter 3 code and can't find onLoad in mixed case. Just curious because we need to fix it ASAP if it is. Other than what was talked about in this thread already, all of the code in the book should be XHTML compliant. Even the code in this thread is XHTML compliant, for that matter, it just requires tweaking to deal with some of the JavaScript DOCTYPE oddities.

-mm
Michael Morrison
Author of Head First JavaScript, Head First PHP & MySQL
0

#14 User is offline   stephee24 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 28
  • Joined: 08-February 08

Posted 10 February 2008 - 12:36 AM

Ah, I should have been more clear. It's not the code in the book that has mixed case but the code in the Ch03 sample files. I just double checked every irock page from the Ch03 sample files and they all have onLoad. I downloaded these yesterday, I think.

Hm, I just realized that you may have been checking different files. I downloaded the bulk zip file that contains every file for every chapter. I just checked the individual files on the individual chapter web pages and they are correct. I guess there is a discrepancy between the bulk download and the individuals.
0

#15 User is offline   stephee24 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 28
  • Joined: 08-February 08

Posted 10 February 2008 - 01:22 PM

I just found more onLoads in the Chapter 5 practice files that I downloaded in the bulk zip file. So, I bet they are in more than just these few chapters.
0

#16 User is offline   Michael Morrison 

  • Active Member
  • PipPipPipPip
  • Group: O'Reilly Author
  • Posts: 114
  • Joined: 16-October 07
  • Location:Nashville, TN
  • Interests:nerdy tinkering, skateboarding, hockey, pond building, landscaping, architecture/construction

Posted 11 February 2008 - 08:35 AM

OK, thanks for double-checking. I have no clue how they are in some versions of the files and not others. I'll go through all of them and get them fixed. As I'm sure you already know, all HTML attributes should be in lowercase.

-mm
Michael Morrison
Author of Head First JavaScript, Head First PHP & MySQL
0

#17 User is offline   loucostello 

  • New Member
  • Pip
  • Group: Members
  • Posts: 1
  • Joined: 10-January 10

Posted 10 January 2010 - 12:49 PM

I preface this with I love your books and the concept behind the teaching style, and I came into this with no JavaScript skills, as a beginner.

I think you need to take a very close look at the idea of manipulating the pet rock width and height as your basic example. Not only is the actual choice of width or height parameter dependent upon the DOM, but the proportional scaling is also dependent upon the DOM.

As a beginner, trying to solve the issues wrapped up in this example was very difficult, enlightening but very hard. And to be honest, I doubt I understand or have correctly solved the problem.

Because the solution depends on understanding the DOM (which I didn't when I started and still don't), learning how to use the Firebug debugger (a Head First book in and of itself), and separating HTML and CSS, this just seems like a poor choice for an entry level problem.

Finally providing an example that only works correctly with no DOM statement goes against everything you've taught in your other books, and frankly is pretty useless when you attempt to take what you've learned and put it into practice.

Also possible errata
Page 103 you state in order to size the pet rock its height should depend "on the height of the client window."

followed by the calculation
"(clientWindowHeight - 100) * 0.9 = rockImageHeight"

but then on page 104 when we fill in our answer for the resizeRock() code the answer is:

"...(document.body.clientHeight - 100) * 0.9"

notice the missing "Window." This becomes key based on the DOM. If instead you had used on page 104

"...(window.innerHeight - 100) * 0.9"

this is self consistent, and seems (and I mean seems) to be DOM and CSS style sheet independent.


For those fighting the battle yourself, cheap advice:
note, I had no idea how to do any of this before attempting to try to solve this problem.

0. If you just want the example to work, and you did what any graduate of previous Head First books did and added a DOM, and separated your CSS stylings - don't. Do the example exactly as it's given, no DOM, use inline styles. It will probably work. Otherwise, if you want to tilt the windmill:

1. Keep the stylings inline. Do not use an external CSS sheet. I know the earlier response tried to use this a fix but it muddies the waters as you try to see what's really happening.

2. Install Firebug. Warning steep learning curve ahead! Open Firefox, bring up Firebug, and then load your Pet Rock html. Go to Firebug's DOM tab and start digging (scrolling and clicking "+" signs). Watch what happens to the window.document.body.clientHeight value as you change the DOM in your Pet Rock html and reload the browser (you need to hit the + signs by document and body along the way to get there). Also right click on the pet rock and check its properties and watch its height along the way. See how the numbers add up and relate to each other.

3. It helps if you install an add-on that lets you measure the actual window size, because with Firebug open your window size changes and might not be what you expect. I used the MeasureIt add-on available from the firefox add-on site.

What I found as I played with this:
Firefox 3.5

html> window.document.body.clientHeight = visible window size available in browser window

xhtml 1.0 transitional> window.document.body. clientHeight = pet rock height + top margin

manipulating "document.getElementById("rockImg").style.height" as given in the book, while using the xhtml DOM, results in a flat pet rock. It does not re size proportionally. Haven't quite yet figured out why, but I agree that the use of "style.height" messes things up by pointing towards a non-existent style sheet parameter (begs the question is an inline style the same as css style to JavaScript? Probably not, and oh, by the way it depends on the DOM you choose :-).

So this was a long comment, but I hope it gives the Head First guys an idea of how a beginner reading their text for understanding can easily get derailed by a poorly chosen example. I love the series, but this example, not so much.


0

#18 User is offline   RenatoPaulo 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 12
  • Joined: 18-January 10

Posted 08 February 2010 - 11:52 AM

I also had this problem. Studying it I realized that:

When we work in quirks mode the elements html and body start by default with the height of the browser window. But when we tell the browser that we are working with XHTML strict, the elements html and body start by default with the height required to contain all the visible elements of the page. For this example, little more than 290px (because of the padding and margin standards).

So I sought something that would inform the actual height of the browser window. I came to a satisfactory result. Also I removed onresize of body of xhtml, since this attribute is no longer accepted. Finally, I separated the code (partially), so that he could be more elegant. Next I want to separate completely style, structure and script.

Below my code:

irock.html
CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>iRock - A Rocha virutal de estimação</title>
<script type="text/Javascript" src="cookies.js"></script>
<script type="text/Javascript" src="irock.js"></script>
<link rel="stylesheet" type="text/css" href="irock.css" />

</head>

<body onload="resizeRock(); greetUser();">
<div>
<img id="rockImg" src="rock.png" alt="iRock" onclick="touchRock(); rochaPrecisaDeAtenção();"/>
</div>
</body>
</html>



irock.css
CODE
div {
text-align: center;
margin-top: 100px;
width
}

img {
cursor: pointer;
}



irock.js
CODE
var userName;

window.onresize = resizeRock;

function greetUser(){
if (navigator.cookieEnabled)
userName = readCookie("irock_username");
if (userName)
alert("Olá " + userName + " senti a sua falta.");
else
alert("Olá, eu sou a rocha de estimação, a iRock.");
}

function resizeRock() {
document.getElementById('rockImg').style.height = (window.innerHeight-100)*0.9 + "px";
}

function touchRock(){
if(userName) {
alert("Eu gosto de atenção " + userName + ". Obrigada.");
}
else {
userName = prompt("Qual o seu nome?", "Entre com o seu nome aqui, por favor.");
if (userName){
alert("Prazer em conhecê-lo, " + userName + ".");
document.getElementById("rockImg").src = "rock_happy.png";
if (navigator.cookieEnabled)
writeCookie("irock_username", userName, 5 * 365);
else
alert("Desculpe" + username + ", mas sem cookies eu tenho dificuldades de me lembrar das coisas. Ative os cookies em seu navegador para uma experiência mais realística");
}
}
}

function rochaPrecisaDeAtenção() {
setTimeout("document.getElementById('rockImg').src = 'rock.png'",5*60*1000);
}



Significant changes in the script:
CODE

window.onresize = resizeRock;
(...)
function resizeRock() {
document.getElementById('rockImg').style.height = (window.innerHeight-100)*0.9 + "px";



PS: The Xhtml and CSS validated.


________________________


Também tive este problema. Estudando-o percebi que:

Quando trabalhamos em quirks mode os elementos html e body iniciam por padrão com a altura da janela do navegador. Porém quando informamos ao navegador que estamos trabalhando com XHTML strict, os elementos html e body iniciam por padrão com a altura necessária para conter todos os elementos visíveis da página. No caso deste exemplo, pouco mais do que 290px (por causa dos padding e margin padrões).

Desta forma busquei algo que informasse a altura real da janela do navegador. Cheguei a um resultado satisfatório. Também retirei o onresize do corpo do xhtml, uma vez que este atributo não é mais aceito. Por fim, separei os códigos (parcialmente), para que ficasse mais elegante. Pretendo em breve deixar separar totalmente estilo, estrutura e ação.

A seguir meus códigos:

irock.html
CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>iRock - A Rocha virutal de estimação</title>
<script type="text/Javascript" src="cookies.js"></script>
<script type="text/Javascript" src="irock.js"></script>
<link rel="stylesheet" type="text/css" href="irock.css" />

</head>

<body onload="resizeRock(); greetUser();">
<div>
<img id="rockImg" src="rock.png" alt="iRock" onclick="touchRock(); rochaPrecisaDeAtenção();"/>
</div>
</body>
</html>



irock.css
CODE
div {
text-align: center;
margin-top: 100px;
width
}

img {
cursor: pointer;
}



irock.js
CODE
var userName;

window.onresize = resizeRock;

function greetUser(){
if (navigator.cookieEnabled)
userName = readCookie("irock_username");
if (userName)
alert("Olá " + userName + " senti a sua falta.");
else
alert("Olá, eu sou a rocha de estimação, a iRock.");
}

function resizeRock() {
document.getElementById('rockImg').style.height = (window.innerHeight-100)*0.9 + "px";
}

function touchRock(){
if(userName) {
alert("Eu gosto de atenção " + userName + ". Obrigada.");
}
else {
userName = prompt("Qual o seu nome?", "Entre com o seu nome aqui, por favor.");
if (userName){
alert("Prazer em conhecê-lo, " + userName + ".");
document.getElementById("rockImg").src = "rock_happy.png";
if (navigator.cookieEnabled)
writeCookie("irock_username", userName, 5 * 365);
else
alert("Desculpe" + username + ", mas sem cookies eu tenho dificuldades de me lembrar das coisas. Ative os cookies em seu navegador para uma experiência mais realística");
}
}
}

function rochaPrecisaDeAtenção() {
setTimeout("document.getElementById('rockImg').src = 'rock.png'",5*60*1000);
}



Alterações importantes no script:
CODE

window.onresize = resizeRock;
(...)
function resizeRock() {
document.getElementById('rockImg').style.height = (window.innerHeight-100)*0.9 + "px";



PS: O Xhtml e as CSS foram validados.
0

#19 User is offline   drewdin 

  • Super Veteran Member
  • PipPipPipPipPipPipPipPipPipPipPip
  • Group: Members
  • Posts: 608
  • Joined: 11-February 10
  • Gender:Male
  • Location:Boston

Posted 21 August 2011 - 01:59 PM

Very helpful answer, got it working for me. thx mm
0

#20 User is offline   ChoiJinYoung 

  • New Member
  • Pip
  • Group: Members
  • Posts: 1
  • Joined: 31-October 11

Posted 31 October 2011 - 09:48 AM

Thank you... your explanation.

because of you I solve this problem.

but Did you test all browser?.. I tested safari, chrome, firefox...and IE8

safari, chrome, firefox pass my test..

but IE8 occur error... The argument is invalid

document.getElementById('rockImg').style.height = (window.innerHeight - 100) * 0.9 + "px";

Do you know? why occur this error?

plz help me..


View PostRenatoPaulo, on 08 February 2010 - 11:52 AM, said:

I also had this problem. Studying it I realized that:

When we work in quirks mode the elements html and body start by default with the height of the browser window. But when we tell the browser that we are working with XHTML strict, the elements html and body start by default with the height required to contain all the visible elements of the page. For this example, little more than 290px (because of the padding and margin standards).

So I sought something that would inform the actual height of the browser window. I came to a satisfactory result. Also I removed onresize of body of xhtml, since this attribute is no longer accepted. Finally, I separated the code (partially), so that he could be more elegant. Next I want to separate completely style, structure and script.

Below my code:

<b>irock.html</b>
<div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>iRock - A Rocha virutal de estimação</title>
<script type="text/Javascript" src="cookies.js"></script>
<script type="text/Javascript" src="irock.js"></script>
<link rel="stylesheet" type="text/css" href="irock.css" />

</head>

<body onload="resizeRock(); greetUser();">
<div>
<img id="rockImg" src="rock.png" alt="iRock" onclick="touchRock(); rochaPrecisaDeAtenção();"/>
</div>
</body>
</html>
</div>


<b>irock.css</b>
<div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'>div {
text-align: center;
margin-top: 100px;
width
}

img {
cursor: pointer;
}
</div>


<b>irock.js</b>
<div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'>var userName;

window.onresize = resizeRock;

function greetUser(){
if (navigator.cookieEnabled)
userName = readCookie("irock_username");
if (userName)
alert("Olá " + userName + " senti a sua falta.");
else
alert("Olá, eu sou a rocha de estimação, a iRock.");
}

function resizeRock() {
document.getElementById('rockImg').style.height = (window.innerHeight-100)*0.9 + "px";
}

function touchRock(){
if(userName) {
alert("Eu gosto de atenção " + userName + ". Obrigada.");
}
else {
userName = prompt("Qual o seu nome?", "Entre com o seu nome aqui, por favor.");
if (userName){
alert("Prazer em conhecê-lo, " + userName + ".");
document.getElementById("rockImg").src = "rock_happy.png";
if (navigator.cookieEnabled)
writeCookie("irock_username", userName, 5 * 365);
else
alert("Desculpe" + username + ", mas sem cookies eu tenho dificuldades de me lembrar das coisas. Ative os cookies em seu navegador para uma experiência mais realística");
}
}
}

function rochaPrecisaDeAtenção() {
setTimeout("document.getElementById('rockImg').src = 'rock.png'",5*60*1000);
}
</div>


<b>Significant changes in the script:</b>
<div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'>
window.onresize = resizeRock;
(...)
function resizeRock() {
document.getElementById('rockImg').style.height = (window.innerHeight-100)*0.9 + "px";</div>


PS: The Xhtml and CSS validated.


________________________


Também tive este problema. Estudando-o percebi que:

Quando trabalhamos em quirks mode os elementos html e body iniciam por padrão com a altura da janela do navegador. Porém quando informamos ao navegador que estamos trabalhando com XHTML strict, os elementos html e body iniciam por padrão com a altura necessária para conter todos os elementos visíveis da página. No caso deste exemplo, pouco mais do que 290px (por causa dos padding e margin padrões).

Desta forma busquei algo que informasse a altura real da janela do navegador. Cheguei a um resultado satisfatório. Também retirei o onresize do corpo do xhtml, uma vez que este atributo não é mais aceito. Por fim, separei os códigos (parcialmente), para que ficasse mais elegante. Pretendo em breve deixar separar totalmente estilo, estrutura e ação.

A seguir meus códigos:

<b>irock.html</b>
<div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>iRock - A Rocha virutal de estimação</title>
<script type="text/Javascript" src="cookies.js"></script>
<script type="text/Javascript" src="irock.js"></script>
<link rel="stylesheet" type="text/css" href="irock.css" />

</head>

<body onload="resizeRock(); greetUser();">
<div>
<img id="rockImg" src="rock.png" alt="iRock" onclick="touchRock(); rochaPrecisaDeAtenção();"/>
</div>
</body>
</html>
</div>


<b>irock.css</b>
<div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'>div {
text-align: center;
margin-top: 100px;
width
}

img {
cursor: pointer;
}
</div>


<b>irock.js</b>
<div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'>var userName;

window.onresize = resizeRock;

function greetUser(){
if (navigator.cookieEnabled)
userName = readCookie("irock_username");
if (userName)
alert("Olá " + userName + " senti a sua falta.");
else
alert("Olá, eu sou a rocha de estimação, a iRock.");
}

function resizeRock() {
document.getElementById('rockImg').style.height = (window.innerHeight-100)*0.9 + "px";
}

function touchRock(){
if(userName) {
alert("Eu gosto de atenção " + userName + ". Obrigada.");
}
else {
userName = prompt("Qual o seu nome?", "Entre com o seu nome aqui, por favor.");
if (userName){
alert("Prazer em conhecê-lo, " + userName + ".");
document.getElementById("rockImg").src = "rock_happy.png";
if (navigator.cookieEnabled)
writeCookie("irock_username", userName, 5 * 365);
else
alert("Desculpe" + username + ", mas sem cookies eu tenho dificuldades de me lembrar das coisas. Ative os cookies em seu navegador para uma experiência mais realística");
}
}
}

function rochaPrecisaDeAtenção() {
setTimeout("document.getElementById('rockImg').src = 'rock.png'",5*60*1000);
}
</div>


<b>Alterações importantes no script:</b>
<div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'>
window.onresize = resizeRock;
(...)
function resizeRock() {
document.getElementById('rockImg').style.height = (window.innerHeight-100)*0.9 + "px";</div>


PS: O Xhtml e as CSS foram validados.

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users