Friday, November 03, 2006

Filters in Internet Explorer

Fade Filter

One of the few IE-only features that I like are filters, and especially the fade transition filter. It just adds a bit more quality to the page, and degrades gracefully in other browsers.

Define the filter in your stylesheet:

div#filterElement { filter: progid:DXImageTransform.Microsoft.Fade(duration=2) height: 20px; width: 100px; background-color: blue; }

One gotcha is that you need to define a width and height for the filters to work. Then add the javascript to perform the transition:

function showDiv(divId) { var myDiv = document.getElementById(divId);'hidden';'block'; if( myDiv.filters) { myDiv.filters[0].Apply(); }'visible'; if( myDiv.filters) { myDiv.filters[0].Play(); } }

Applying a filter effectively takes a snapshot of the element at that point in time. You then change its state behind the scenes, then Play() the transition, so in this case it blends between the state at Apply() and the state at Play(). Don't hide the element (display: none;) because doesn't display the element at all, and the transition is hidden from view. Using visibility: hidden keeps the element in place, but hides its contents.

Hiding the element is a bit more tricky, because the transition doesn't block the javascript, and so you hide the element immendiately after you start playing the transition, and the transition is hidden too. You therefore have to use the onfilterchange event on your element (IE only).

function hideDiv(myDiv) { if( myDiv.filters) { myDiv.filters[0].Apply(); }'hidden'; if( myDiv.filters) { myDiv.filters[0].Play(); } } function removeDiv(myDiv) { if( == 'hidden' ) {'none'; } }

Then, put the event on the element to remove the element from the page:

<div onclick="showDiv('filterElement')">Click to show</div> <div id="filterElement" onclick="hideDiv(this)" onfilterchange="removeDiv(this)">Click to hide</div>


Post a Comment

<< Home