jQuery unveiled: the css() method

The css() jQuery method requires two steps: first jQuery defines some filters to be applied to the CSS properties, then specifies the actual method:

var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
 ralpha = /alpha\([^)]*\)/,
 ropacity = /opacity=([^)]*)/,
 rfloat = /float/i,
 rdashAlpha = /-([a-z])/ig,
 rupper = /([A-Z])/g,
 rnumpx = /^-?\d+(?:px)?$/i,
 rnum = /^-?\d/,

 cssShow = { position: "absolute", visibility: "hidden", display:"block" },
 cssWidth = [ "Left", "Right" ],
 cssHeight = [ "Top", "Bottom" ],

 // cache check for defaultView.getComputedStyle
 getComputedStyle = document.defaultView && document.defaultView.getComputedStyle,
 // normalize float css property
 styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat",
 fcamelCase = function( all, letter ) {
  return letter.toUpperCase();
 };

jQuery.fn.css = function( name, value ) {
 return access( this, name, value, true, function( elem, name, value ) {
  if ( value === undefined ) {
   return jQuery.curCSS( elem, name );
  }
  
  if ( typeof value === "number" && !rexclude.test(name) ) {
   value += "px";
  }

  jQuery.style( elem, name, value );
 });
};

Filters are used to exclude the CSS properties in order to add pixels to the style definitions. Then jQuery checks if the W3C DOM method getComputedStyle() is supported or not and if the browser in question supports the CSS float property as cssFloat or styleFloat. The actual css() method performs two tasks:

  1. if the style value passed in is undefined, returns the computed style of the current element for the specified property
  2. if a property can accept pixels as its values and if px has not been specified (ie. the value passed in is a number), it adds px to the CSS value
  3. applies the specified styles to the current element.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.