PDA

View Full Version : Opera & offsetWidth


IKLOP
04-06-2004, 11:37 PM
Hello,
I am trying to get the width of a cell of a table using javascript using this code:

for(var i=0; i<columns; i++)
{
var widths[i] = document.getElementById('table').rows[0].cells[i].offsetWidth;
}

This works fine in Mozilla and IE, but in Opera it does not include the padding of the cell so the values are all shorter than the actual widths. Is there another way that I can get the real width and not the width minus padding?

Thanks,
- Steve

agent002
04-07-2004, 08:42 AM
There might be but I don't know, so try this function that I made for you instead.
var isOpera = (navigator.userAgent.indexOf('Opera') >= 0);

function cbcOffsetWidth(e){
var ret = e.offsetWidth;
if(isOpera && e.style.paddingLeft)
ret += parseInt(e.style.paddingLeft);
if(isOpera && e.style.paddingRight)
ret += parseInt(e.style.paddingRight);
return ret;
}

function cbcOffsetHeight(e){
var ret = e.offsetHeight;
if(isOpera && e.style.paddingTop)
ret += e.style.paddingTop;
if(isOpera && e.style.paddingBottom)
ret += e.style.paddingBottom;
return ret;
}
haven't tested it, dunno if it works, but try using it like
for(var i=0; i<columns; i++)
{
var widths[i] = cbcOffsetWidth(document.getElementById('table').rows[0].cells[i]);
}
:)

n8thegreat
04-07-2004, 08:51 AM
you can only access the padding values of the element like that if they are declared inline, you can try this:
parseInt(document.defaultView.getComputedStyle(YOUR OBJECT HERE, "").getPropertyValue("width"))

note: that does not work in IE.
also, it may not include any of the padding if you dont have a background color or image. i have experienced that in the past.

IKLOP
04-07-2004, 12:38 PM
I used agents method. Since all my cells have the same padding I don't have to use style.padding and I can just use a constant. Works now.

Thanks,
-Steve

agent002
04-07-2004, 12:43 PM
I'd like to thank nate for correcting me and also suggest you to still use his method... if it works in Opera. If you go change the paddings you can't use a constant value anymore, and that way the script would be much more portable in case you need it somewhere else too. I suppose nate's code thingy works like:
var isOpera = (navigator.userAgent.indexOf('Opera') >= 0);

function cbcOffsetWidth(e){
var ret = e.offsetWidth;
if(isOpera)
ret += parseInt(document.defaultView.getComputedStyle(e, '').getPropertyValue('padding-left')) +
parseInt(document.defaultView.getComputedStyle(e, '').getPropertyValue('padding-right'));
return ret;
}

function cbcOffsetHeight(e){
var ret = e.offsetHeight;
if(isOpera)
ret += parseInt(document.defaultView.getComputedStyle(e, '').getPropertyValue('padding-top')) +
parseInt(document.defaultView.getComputedStyle(e, '').getPropertyValue('padding-bottom'));
return ret;
}
:)