jQuery in Action
64
CHAPTER 3
Bringing pages to life with jQuery
To retrieve the width or height:
The fact that the width and height values are returned from these functions as
numbers isn't the only convenience that these commands bring to the table. If
you've ever tried to find the width or height of an element by looking at its
numbers isn't the only convenience that these commands bring to the table. If
you've ever tried to find the width or height of an element by looking at its
style.width
or
style.height
property, you were confronted with the sad fact that
these properties are only set by the corresponding
style
attribute of that ele-
ment; to find out the dimensions of an element via these properties, you have to
set them in the first place. Not exactly a paragon of usefulness!
set them in the first place. Not exactly a paragon of usefulness!
The
width()
and
height()
commands, on the other hand, compute and
return the size of the element. Although knowing the precise dimensions of an
element in simple pages that let their elements lay out wherever they end up isn't
usually necessary, knowing such dimensions in Rich Internet Applications is cru-
cial to be able to correctly place active elements such as context menus, custom
tool tips, extended controls, and other dynamic components.
element in simple pages that let their elements lay out wherever they end up isn't
usually necessary, knowing such dimensions in Rich Internet Applications is cru-
cial to be able to correctly place active elements such as context menus, custom
tool tips, extended controls, and other dynamic components.
Let's put them to work. Figure 3.3 shows a sample set up with two primary ele-
ments: a test subject
<div>
that contains a paragraph of text (also with a border
Command syntax: width and height
width()
height()
Retrieves the width or height of the first element of the wrapped set
Parameters
none
Returns
The computed width or height as a number
The computed width or height as a number
Figure 3.3 The width and height of the test element aren't fixed and depend on the width of the
browser window.
browser window.