jQuery unveiled: the style() method

The style() method is a private method used by jQuery to handle CSS styles through the css() public method. It is as follows:

style: function( elem, name, value ) {
  // don't set styles on text and comment nodes
  if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
   return undefined;
  }

  // ignore negative width and height values #1599
  if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) {
   value = undefined;
  }

  var style = elem.style || elem, set = value !== undefined;

  // IE uses filters for opacity
  if ( !jQuery.support.opacity && name === "opacity" ) {
   if ( set ) {
    // IE has trouble with opacity if it does not have layout
    // Force it by setting the zoom level
    style.zoom = 1;

    // Set the alpha filter to set the opacity
    var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")";
    var filter = style.filter || jQuery.curCSS( elem, "filter" ) || "";
    style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity;
   }

   return style.filter && style.filter.indexOf("opacity=") >= 0 ?
    (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "":
    "";
  }

  // Make sure we're using the right name for getting the float value
  if ( rfloat.test( name ) ) {
   name = styleFloat;
  }

  name = name.replace(rdashAlpha, fcamelCase);

  if ( set ) {
   style[ name ] = value;
  }

  return style[ name ];
 },

  1. skips text nodes and comment nodes by returning undefined
  2. ignores negative width and height values by using the parseFloat function
  3. checks if the browser supports natively the opacity property; if the browser is Internet Explorer, uses its proprietary filter property instead by giving first layout to the current element
  4. checks if the browser uses cssFloat or styleFloat as its JavaScript equivalent of the CSS float property
  5. returns an object containing a set of property/value pairs (one or more).

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.