views:

1274

answers:

3

The following jQuery code works just fine for me with Safari, Opera, FF2, and FF3. It positions a busy DIV (with an animated busy GIF) on top of a FORM element on my web page. The problem is that in IE6 and IE7, it gets width and height properly, but doesn't seem to get top and left properly. What's the catch?

var nH = $('#' + sForm).attr('offsetHeight');
var nW = $('#' + sForm).attr('offsetWidth');
var nT = $('#' + sForm).attr('offsetTop');
var nL = $('#' + sForm).attr('offsetLeft');

$('#busy')
 .css('position','absolute')
 .css('height', nH + 'px')
 .css('width', nW + 'px')
 .css('top', nT + 'px')
 .css('left', nL + 'px')
 .show();

Note that on my page I have multiple FORM elements. (The reason for the busy GIF is because I'm doing an AJAX post in the background when a form is submitted.)

Note I also tried the jQuery Dimensions Plugin 1.2's .position() value for top and left, and that helped, but seemed to have the 'top' value become more off the further I moved down in the page.

A: 

I got it to work with the jQuery Dimensions Plugin 1.2's .position() value for top and left. (It returns an array where you can get top and left array values.) The fix was that I have to trap for IE6 and just subtract some fixed number (12px in my case) for top, and add that same number on height. On IE7, I could do the same thing, but had to do the top and height math differently for some reason on the first 200 pixels or less. Your situation may be different, depending on your previous CSS, your reset.css, and so on.

A: 

Are you sure the element is set to display:block? Also you can avoid multiple calls to the css function by passing a hash like this:

$('#busy')
    .css({'position':'absolute',
          'height': nH + 'px',
          'width', nW + 'px',
          'top', nT + 'px',
          'left', nL + 'px'})
    .show();
brian
Thanks for that tip. I wasn't thinking of the performance hit, and I should have been. You are right.
+1  A: 

Right now jQuery (latest public release) includes dimensions as core functions.

Try using $(element).offset() (it returns an object with "left" and "top" properties). I've used it a lot and works just perfect for many many browsers (ie6/7, opera, safari, chrome, ff2/3)

Ricardo Vega
Thanks for the tip. Seems like I can stop using the jQuery Dimensions Plugin. I'll give it a try to see if offset does the trick for me. Could be one more thing to speed up a web page and please YSlow.