jQuery: object detection and hasLayout

When it comes to CSS bugs, there is only one name that often occurs in the nightmares of web developers: Internet Explorer 6 and 7. The problem with these two browsers is that they're affected by the hasLayout property. hasLayout is a JavaScript read-only property that is attached to every single element on the page. It has a Boolean value that tells IE if a given element has layout or not. Depending on whether an element has layout or not, certain bugs may occur or not.

The syntax of this property is as follows:


To detect if we're dealing with IE 6 and 7 and with hasLayout, we could write something like this:

var test = $('#test')[0];
alert(test.currentStyle.hasLayout); // true or false

Note that we're using the bracket notation to access the above test element. By doing so, we can use DOM and JavaScript properties and methods which are not directly accessible within the jQuery global wrapper ($). We can also improve our routine with a try.. catch block:

try {
} catch(e) {
  alert('hasLayout not supported!');

Using object detection for hasLayout allows us to check if we're dealing with IE 6 and 7. What's more, we might also add a bug fixing routine, like so:

if(!test.currentStyle.hasLayout) {
    if($('#test').css('display') == 'block') {
        $('#test').css('height', '1%');
    } else if($('#test').css('display') == 'inline') {
        $('#test').css('zoom', '1');

Of course we can also use different CSS classes. Here CSS styles have been inserted through jQuery just for the sake of simplicity.

Leave a Reply

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