Perfection kills

Exploring Javascript by example

Archives Posts

Feature testing CSS properties

May 11th, 2009 by kangax

Contrary to many beliefs, detecting CSS properties support with Javascript is not very complicated. One of the CSS-related tests in Common Feature Tests suite is IS_CSS_BORDER_RADIUS_SUPPORTED which looks as simple as this:

var IS_CSS_BORDER_RADIUS_SUPPORTED = (function() {
  var docEl = document.documentElement, s;
  if (docEl && (s = docEl.style)) {
      return typeof s.borderRadius == "string" 
        || typeof s.MozBorderRadius == "string" 
        || typeof s.WebkitBorderRadius == "string" 
        || typeof s.KhtmlBorderRadius == "string";
  }
  return null;
})();

As you can see, testing a CSS property boils down to an inference drawn from the presence of the same named property in a style of an arbitrary element. If you wanted to test support for a “marginLeft” property, you would do it like so:

var el = document.createElement('div');
typeof el.style.marginLeft == 'string'; // true
typeof el.style.marginLeft2 == 'string'; // false

An alternative (and less verbose) way involves replacing typeof operator with in operator:

var el = document.createElement('div');
'marginLeft' in el.style; // true
'marginLeft2' in el.style; // false

in was actually used in earlier versions of CFT but I find such inference too weak. in doesn’t check type of a property; it merely determines property existence, and would return true even if it had undefined (or any other, non-string) value.

IS_CSS_BORDER_RADIUS_SUPPORTED doesn’t just test CSS3 “borderRadius” property. It also tries some of the known proprietary, vendor-specific variations – “MozBorderRadius”, “WebkitBorderRadius” and “KhtmlBorderRadius”. While tweaking this test a couple of days ago, I realized that if I wanted to test CSS3 “boxShadow” property, I would need to follow the same logic and “iterate” over the very same prefixes – “MozBoxShadow”, “WebkitBoxShadow” and so on. Such duplication was clearly not the way to go and a more generic function seemed like a better solution.

getStyleProperty

What it all led to was a very simple getStyleProperty helper:

var getStyleProperty = (function(){
 
  var prefixes = ['Moz', 'Webkit', 'Khtml', 'O', 'Ms'];
 
  function getStyleProperty(propName, element) {
    element = element || document.documentElement;
    var style = element.style,
        prefixed;
 
    // test standard property first
    if (typeof style[propName] == 'string') return propName;
 
    // capitalize
    propName = propName.charAt(0).toUpperCase() + propName.slice(1);
 
    // test vendor specific properties
    for (var i=0, l=prefixes.length; i<l; i++) {
      prefixed = prefixes[i] + propName;
      if (typeof style[prefixed] == 'string') return prefixed;
    }
  }
 
  return getStyleProperty;
})();

getStyleProperty follows the same logic and returns a first found CSS property on an arbitrary (or optionally specified) element. If you run getStyleProperty('borderRadius') in Mozilla-based browser, it would return “MozBorderRadius”; if it was a Webkit-based client, a “WebkitBorderRadius” would be returned. Finally, if no property was found, methods would exit with undefined.

Simple as that.

The way you would test a property is by comparing returned result’s type to “string”:

if (typeof getStyleProperty('borderRadius') == 'string') {
  // property is supported
}

I didn’t want to recreate a prefixes array every time function is called and stored it in a closure. I also used function declaration inside that closure, rather than returning an anonymous function expression, so that getStyleProperty had a descriptive identifier. There’s a document.documentElement used as a generic element (in case none is provided as a second argument), but I could as well have created a new one with document.createElement.

You’re obviously free to improvise with these subtleties as you find appropriate, as long as the actual testing mechanism is left intact.

Performance considerations

I don’t consider execution speed very crucial for a method such asgetStyleProperty, since it would most likely be executed once or twice and probably during the load time. Nevertheless, two basic optimizations come to mind.

Caching a property is one of them. We can simply create a “private” object that maps original (passed into function) property to an actual (possibly prefixed) one and use that object as a cache:

var getStyleProperty = (function(){
 
  var prefixes = ['Moz', 'Webkit', 'Khtml', 'O', 'Ms'];
  var _cache = { };
 
  function getStyleProperty(propName, element) {
    element = element || document.documentElement;
    var style = element.style,
        prefixed,
        uPropName;
 
    // check cache only when no element is given
    if (arguments.length == 1 && typeof _cache[propName] == 'string') {
      return _cache[propName];
    }
    // test standard property first
    if (typeof style[propName] == 'string') {
      return (_cache[propName] = propName);
    }
 
    // capitalize
    uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
 
    // test vendor specific properties
    for (var i=0, l=prefixes.length; i<l; i++) {
      prefixed = prefixes[i] + uPropName;
      if (typeof style[prefixed] == 'string') {
        return (_cache[propName] = prefixed);
      }
    }
  }
 
  return getStyleProperty;
})();

Another optimization is to cache vendor prefix, such as “Moz” or “Webkit” rather than a specific property. An assumption we’re making here is that if one prefixed property is found in an element’s style, than that prefix can safely be prepended to any other property resulting in a “proper” string. I’m not sure if such inference is a good thing, since clients are obviously not limited to implementing only one type of vendor-specific properties; I can imagine Khtml-based clients implementing both – Khtml- and Webkit- properties.

It might be safer to just stick to “regular” caching mechanism (if any at all), as in the previous snippet.

Inference downsides

Theoretically speaking, the inference we are relying on for getStyleProperty is not all that strong. A mere existence of a CSS property doesn’t tell us about an actual implementation and its conformance to a specification. A browser might have “borderRadius” property with a proper string value; it could allow to assign to that property and even set its value to a specified one after assignment; yet, it could never make borders rounded. The problem is that many CSS3 declarations affect document in such way that it is impossible to detect their effect on a DOM. Border’s radius and box’s shadow, text’s stroke and text overflow (ending with an ellipsis) are all purely visual aspects. If “marginLeft” conformance can be checked by testing element’s offset (as it is represented in a DOM), most of the CSS3 properties don’t provide such luxury.

This is an important thing to remember.

CFT

getStyleProperty is now part of CFT suite (source of which you can find on github). There’s also a simple test page with some of the common CSS3 properties tested.

As always, I’d love to hear any suggestions/corrections you have.

Archives Posts

Misbehaving IE8

January 29th, 2009 by kangax

When testing IE8 Beta 2 a couple of months ago, I noticed how one innocent line would bring poor pal to its knees:

  Element.prototype.cloneNode.call();

Go ahead, try it out. It crashes my browser. Does it crash yours? A few days ago, Release Candidate 1 came out. The “magic” expression still crashes my browser… This doesn’t apply to cloneNode only. Most if not all of the Element.prototype methods (as well as some others) fail in the very same way:

Element.prototype.appendChild.call();
Element.prototype.hasChildNodes.call();
document.querySelector.call();

I tried submitting a bug to IE team few times but only kept getting errors in bug tracker. Here’s hoping to a more stable RC2!

Filed under Uncategorized having 6 Comments »

Archives Posts

Proto.IPS – In place select widget

December 22nd, 2007 by kangax

Proto.IPS

In place editing is a great way to enhance user interface when dynamically changing data on a page. Scriptaculous’ In Place Editor is a nice extension with extensive set of features and options. I recently needed such functionality in one of the projects, but IPE wasn’t exactly the best tool for the job. The idea was to let users select one of the predefined options as well as add their own. GMail chat widget and the way it allows to change availability status is a great example of such user interface addition. Another concern was to make control fit in a limited space – google simply gets rid of “Save”/”Cancel” buttons and saves value of the input field when clicking outside of control.

I tried duplicating this behavior into a simple prototype based script which can be simply plugged into any project.
This work is experimental (there are couple of known issues) and I would appreciate any feedback.

Head over to a demo page and let me know what you think.

Filed under Uncategorized having 14 Comments »

« Previous Entries Next Entries »