Getting and setting styles

Modifying the class of an element allows you to choose which predetermined set of defined style sheet rules should be applied. But sometimes you only want to set the value of one or very few properties that are unknown in advance; thus a class name doesn’t exist. Applying styles directly on the elements (via the style property available on all DOM elements) will automatically override the style defined in style sheets (some exceptions such as !important apply, but we aren’t going to cover CSS specificity in detail here), giving you more fine-grained control over individual elements and their styles.

The jQuery css() method allows you to manipulate these styles, working in a similar fashion to attr(). You can set an individual CSS style by specifying its name and value, or a series of styles by passing in an object.

Method syntax: css
css(name, value) css(properties)
Sets the named CSS style property or properties to the specified value for each matched element.
Parameters
name(String) The name of the CSS property to be set. Both the CSS and DOM formatting of multiple-word properties (for example background-color versus backgroundColor) are supported. Most of the time you’ll use the first format version.
value(String|Number|Function) A string, number, or function containing the property value. If a number is passed, jQuery will convert it to a string and add “px” to the end of that string. If you need a different unit, convert the value to a string and add the appropriate unit before calling the method. If a function is passed as this parameter, it will be invoked for each element of the collection, setting the element as the function context (this). The function is passed two values: the element index and the current value. The returned value serves as the new value for the CSS property.
properties(Object) Specifies an object whose properties are copied as CSS properties to all elements in the set.
Returns
The jQuery collection.

The value argument can also be a function in a similar fashion to the attr() method. This means that you can, for instance, expand the width of all elements in the set by 20 pixels times the index of the element as follows:

$('.expandable').css('width', function(index, currentWidth) {
   return parseInt(currentWidth, 10) + 20 * index;
});

In this snippet you need to pass the current value to parseInt() because the width of an element is returned in pixels and as a string (for example, "50px"). Without a conversion, the sum will act as a concatenation of strings resulting in a value like "50px20" (if the value of index is 1).

In case you want to expand the width of all the elements by 20 pixels, jQuery offers you a nice shortcut. Instead of writing a function, you can write

$('.expandable').css('width', '+=20');

A similar shortcut is available if you want to subtract a given amount of pixels:

$('.expandable').css('width', '-=20');

One interesting side note—and yet another example of how jQuery makes your life easier—is that the normally problematic opacity property will work perfectly across browsers (even older ones) by passing in a value between 0.0 and 1.0; no more messing with the old IE alpha filters!

Now let’s see an example of use of the second signature of the css() method:

$('p').css({
   margin: '1em',
   color: '#FFFFFF',
   opacity: 0.8
});

This code will set the values specified to all the elements in the set. But what if you want to create a descending opacity effect with your elements?

As in the shortcut version of the attr() method, you can use functions as values to any CSS property in the property’s parameter object, and they will be called on each element in the set to determine the value that should be applied. You can achieve this task by using a function as the value of opacity instead of a fixed number:

$('p').css({
   margin: '1em',
   color: '#1933FF',
   opacity: function (index, currentValue) {
      return 1 - ((index % 10) / 10);
   }
});

An example of a page using this code can be found in file lesson-5/descending.opacity .html and as a JS Bin.

Lastly, let’s discuss how you can use css() with a name or an array of names passed in to retrieve the computed style of the property or properties associated with that name(s) of the first element in the jQuery object. When we say computed style, we mean the style after all linked, embedded, and inline CSS has been applied.

Method syntax: css
css(name)
Retrieves the computed value or values of the CSS property or properties specified by name for the first element in the set
Parameters
name(String|Array) Specifies the name of a CSS property or array of CSS properties whose computed value is to be returned
Returns
The computed value as a string or an object of property-value pairs

This variant of the css() method always returns values as a string, so if you need a number or some other type, you’ll need to parse the returned value using parseInt() or parseFloat() depending on the situation.

To understand how the getter version of css() works when you pass an array of names, let’s see an example. The goal is to print on the console the property and its corresponding value of an element having special as its class for the following properties: font-sizecolor, and text-decoration. To complete the task, you have to write this:

This code can be found in the file lesson-5/css.and.array.html and as a JS Bin. Loading the page (or the JS Bin) in your browser, you can see how the values printed are the result of the combination of all the styles defined in the page. For example, the value printed for font-size isn’t "20px" but "24px". This happens because the value defined for the special class (24px) has more specificity than the one defined for the div elements (20px).

The css() method is another example of how jQuery solves a lot of cross-browser incompatibilities for you. To achieve this goal using native methods, you should use getComputedStyle() in all the versions of Chrome, Firefox, Opera, Safari, and Internet Explorer starting from version 9 and use the currentStyle and runtimeStyle properties in Internet Explorer 8 and below.

Before moving on, we want to highlight two important facts. The first fact is that different browsers may return CSS color values that are logically but not textually equal. For example, if you have a declaration like color: black; some browsers may return #000#000000, or rgb(0, 0, 0). The second is that the retrieval of shorthand CSS properties such as margin or border is not guaranteed by jQuery (although it works in some browsers).

For a small set of CSS values that are commonly accessed, jQuery provides convenience methods that access these values and convert them to the most commonly used types.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *