Size matters

We have showed a picture to the user. The issue now is that we have no idea of the client window size, that means our picture could be look to the user ridiculy small, or too huge to be seen completely.

So we should rescale the image, and we can do that changing the height (part of the style attribute) for our image, referring to the clientHeight of the document body.

We create a function to do this job:

function resizeMe() {
document.getElementById("rock").style.height =
(document.body.clientHeight - 100) * 0.9;

We want call this function as soon as the page is loaded, so we put it in the onload attribute of the body tag:

<body onload="resizeMe(); greet();">
<!-- ... -->

It is worth noting that it is possible to insert code snippet as argument for the onload attribute, and not just the name of a function.

The attribute onload is the event handler called when the page is loaded for the first time, or reloaded by the user (clicking on F5, for instance). But what we can do to resize our image when the user resize the browser window? Easy solution: we use the onresize attribute:

<body onload="resizeMe(); greet();" onresize="resizeMe()">
<!-- ... -->

But beware: even if onresize is widely used, it is not (yet) a standard attribute. It should be part of HTML5.

Based on an example found in chapter three of Head First JavaScript, a good book for a new starter.

No comments:

Post a Comment