O'Reilly logo

Beginning JavaScript® and CSS Development with jQuery by Richard York

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. CSS

When working with CSS from JavaScript, there are a few minor points of verbosity and inconsistency where jQuery lends a helping hand. First, jQuery makes it easier to manipulate CSS from JavaScript. jQuery's approach allows you to define 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 I mentioned in Chapter 4 and in Chapter 1, it's generally good practice to avoid mixing style (CSS) with behavior (JavaScript) and/or structure (HTML). You want to keep CSS, JavaScript, and HTML partitioned as cleanly as possible into their respective documents.

In some cases, however, it is unavoidable to bring presentation into your JavaScript programming. 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. In this short chapter, I cover the methods that jQuery exposes that let you work with style-sheet properties and values.

The css() Method

Instead of messing around with the style property as you're used to doing with traditional JavaScript, when you want to access style information or modify style information with jQuery, you use jQuery's css() method. The css() method can be used in three different ways:

  • To return a property's value from the first element matched in a selection

  • To set a property's value ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required