Friday, July 24, 2009

Internet Explorer and CSS classes

Programming with jQuery an interactive menu to my work website, I realize a curious behavior of Internet Explorer(IE), why not.

Everytime that you  use jQuery code like this: 

$(this).addClass("clicked");

You will see an erratic behavior. If the element (this) have more than one class, the IE have problems to resolve the heritance and procedence to finaly apply the desired style. But this works with others browsers like Firefox(FF) or Chrome.

The only way I know to avoid this, it is use the css jQuery function. In facts, this function does a style attribute definition in the element. By example, suppose a li element like the following:

<li id="li_0" class="classLi otherClass andOtherClass">
<a href="#">Testing element</a>
</li>


and run this jQuery code:

$("#li_0").css( { 'background-color' : '#C0C0C0', 'color': '#FFFFFF'} );

The li element inside the DOM will be setting like this:

<li id="li_0" class="classLi otherClass andOtherClass" style="background-color: #C0C0C0; color: #FFFFFF;">
<a href="#">Testing Element</a>
</li>


And because the style attribute of an element has dominance over every previous CSS definitions, you will get the desired effect. Using this, IE and FF can have the same final behavior.

Useful link: http://www.visualjquery.com/

No comments: