Web Development with jQuery®

(Elliott) #1

CSS


When working with CSS from JavaScript, a few minor points of verbosity and inconsistency
exist where jQuery can lend a helping hand. jQuery makes it easier to manipulate CSS from
JavaScript. jQuery’s approach enables you to defi ne styles for multiple CSS properties at once,
or one CSS property at a time. But instead of setting CSS properties one element at a time, you
can set the style on one or many elements at once.

As mentioned in Chapter 4, “Manipulating Content and Attributes,” and in Chapter 1,
“Introduction to jQuery,” it’s generally good practice to avoid mixing style (CSS) with behav-
ior (JavaScript) and structure (HTML). You want to keep CSS, JavaScript, and HTML parti-
tioned as cleanly as possible into their respective documents.

In some cases, however, it is unavoidable to bring presentation into your JavaScript program-
ming; for example, it may have already been done the wrong or more-diffi cult-to-maintain
way long before you ever arrived. In these cases, the style changes dynamically in such a way
that it is impractical and unreasonable to keep CSS only in a style sheet and not directly
modify style with JavaScript programming. This chapter covers the methods that jQuery
exposes that enable you to work with style-sheet properties and values.

Working with CSS Properties


Instead of messing around with the style property as you may be used to doing with tradi-
tional JavaScript, when you want to access style information or modify style information with
jQuery, you use jQuery’s css() method. You can use the css() method in three different ways:

➤ (^) To return a property’s value from the fi rst element matched in a selection
➤ (^) To set a property’s value on one or more elements
➤ (^) To set multiple properties on one or more elements
When you simply want to get a property’s value for an element, this is what you do:
var backgroundColor = $('div').css('backgroundColor');


6


http://www.it-ebooks.info

Free download pdf