Web Development with jQuery®

(Elliott) #1

Obtaining Outer Dimensions (^) ❘ 167


jQuery’s Pseudo-Classes


In CSS the pseudo-class marks a condition or state. For example, the :hover pseudo-class is for styling
an element when the mouse cursor comes over the element. The styles that you specify for the :hover
state are only in effect while the mouse cursor resides above an element. jQuery adds a few pseudo-
classes that make more sense in the JavaScript world than in the CSS world.

Some pseudo-classes that jQuery provides are not feasible in CSS. For example, jQuery’s :parent
pseudo-class moves a selection from one or more elements to the parent element(s) of that/those
element(s). This cannot be done in CSS because of the incremental rendering rule. A style sheet
must be applied as it is downloaded to a DOM that is being created as it may also be downloading.
Because of the incremental rendering rule, which is part of what can make a browser appear to load
a page blazingly fast, having to step backward in the DOM poses a technical challenge similar to
reversing the fl ow of a river. If everything is built to fl ow in one direction, from the bottom up, going
from the top to the bottom introduces hurdles, obstacles, and potential glitches. For this reason, the
W3C’s CSS working group has been resistant to introduce any type of parent or ancestor selector.

In JavaScript, however, there are no such limitations. You’re most likely already waiting for the
DOM and, by extension, the associated style sheets to be loaded before you do things with the
document.

NOTE All of jQuery’s pseudo-class extensions, in addition to the various types
of standard selectors supported by jQuery, are documented in Appendix B,
“CSS Selectors Supported by jQuery.”

Obtaining Outer Dimensions


In traditional JavaScript, when you want to get the width of an element—which includes the CSS
width, in addition to border width and padding width—you use the property offsetWidth. Using
jQuery, this information is available when you call the method outerWidth(), which provides the
offsetWidth of the fi rst element in a selection. This gives you a pixel measurement including width,
border, and padding. Likewise, the outerHeight() method does the same with height; it includes CSS
height, padding height, and border height.

NOTE You can also ask for margin length to be included in the return value by
setting the fi rst argument to outerWidth() or outerHeight() to true.

To demonstrate how you would use the css(), outerWidth(), and outerHeight() methods, the fol-
lowing example, Example 6-1, shows you how to make a custom context menu that leverages these
methods to set a custom context menu’s position within the document. The context menu is the

http://www.it-ebooks.info

Free download pdf