Sunday, September 26, 2010

Dynamic floating DIV

I have been having trouble with floating DIV previously. It does not have any problem when running. However, in IE it always appear behind INPUT's. No matter how much I tried, it just don't go away. After searching the web, there seems to be no solution - at least for IE6 and below.

Besides this issue, the CSS for "position" also caused a lot of headache. "Position:fixed" does not work for IE7 (not sure about IE8 and above). "Position:absolute" has to be used. The problem is that this CSS does not make the DIV stay at the defined position.

I have read from post by others that there is only one choice for IE. Use "Position:absolute" and then add a javascript "window.onscroll" event and set the top and left style property of the DIV element using the scrollTop and scrollLeft offsets respectively.

It is not the best solution for IE as when you scroll the DIV actually jumps a bit. It is still better than nothing right?

Positioning the div itself on the top of the screen is no big issue. What if you want to position the DIV somewhere at the bottom of the page? Surely you have to take into consideration of the height of the DIV to ensure that it does not goes beyond the display.

It will be much more difficult if your DIV changes its size dynamically. Fortunately there is a element.offsetHeight/offsetWidth to help. It is the actual height/width of the element even if you set the style.height to auto.

One more thing. If you want to set the DIV to be at a fixed percentage of the window size instead of a fixed pixle value, you have a problem if your DIV is near the bottom of the window. When you resize the window, the div may shifts accordingly and get hidden or shifts up too high.

Therefore, you will need to offset the percentage with the offsetHeight of the DIV. To do that, you will need to know the height of the window.

The problem is that the height of the window can mean different thing in different browsers. This is especially true for different IE versions and whether it is set to quirk mode.

A easy way out is to do this.


var root = (document.compatMode == "CSS1Compat"?
document.documentElement: document.body);
var myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myHeight = window.innerHeight;
} else
myHeight=root.clientHeight

Doing offset is then easy if the height of the window is known. First find out what is the pixel by multiplying the window size with the percent. If the pixle value plus the offsetHeight of the DIV is greater than the window size, then just set it to the window size minus the offsetHeight so that the DIV can be shown all the time.

No comments:

Post a Comment