jQuery in Action
Changing element styling
65
and background color for emphasis) and a second
<div>
in which to display
the dimensions.
The dimensions of the test subject aren't known in advance because no style
rules specifying dimensions are applied. The width of the element is determined
by the width of the browser window, and its height depends on how much room
will be needed to display the contained text. Resizing the browser window would
cause both dimensions to change.
by the width of the browser window, and its height depends on how much room
will be needed to display the contained text. Resizing the browser window would
cause both dimensions to change.
In our page, we define a function that will use the
width()
and
height()
com-
mands to obtain the dimensions of the test subject
<div>
(named
testSubject
)
and display the resulting values in the second
<div>
(named
display
).
function report() {
$('#display').html(
$('#testSubject').width()+'x'+$('#testSubject').height()
);
}
We call this function in the ready handler of the page, resulting in the display of
the values 675 and 48 for that particular size of browser window, as shown in fig-
ure 3.3.
the values 675 and 48 for that particular size of browser window, as shown in fig-
ure 3.3.
We also add a call to the function in the
onresize
attribute of the
<body>
element:
<body onresize="report();">
Resizing the browser results in the display shown in figure 3.4.
This ability to determine the computed dimensions of an element at any point
is crucial to accurately positioning dynamic elements on our pages.
The full code of this page is shown in listing 3.1 and can be found in the file
chapter3/dimensions.html.
Figure 3.4
Resizing the browser causes
the test subject to change
size; this change is reflected
in the computed values.
the test subject to change
size; this change is reflected
in the computed values.