1

I have the need to test the offsetWidth and offsetHeight of an element. Presently, the element is attached and then the offsetWidth and Height are tested, after which the element is remove.

It looks like this:

var sizer = document.createElement('DIV');
sizer.innerHTML = element; //element is a string
document.body.appendChild(sizer);
if (sizer.offsetWidth > maxWidth) {
    sizer.style.width = maxWidth);
}
document.body.removeChild(sizer);

But that is VERY SLOW!

EDIT: Complete code:

InfoBubble.prototype.getElementSize_ = function (element, opt_maxWidth, opt_maxHeight) {
var sizer = document.createElement('DIV');
sizer.style.display = 'inline';
sizer.style.position = 'absolute';
sizer.style.visibility = 'hidden';

 if (typeof element == 'string') {
    sizer.innerHTML = element;
 } else {
    sizer.appendChild(element.cloneNode(true));
 }

 document.body.appendChild(sizer);

 // If the width is bigger than the max width then set the width and size again
 if (opt_maxWidth && sizer.offsetWidth > opt_maxWidth) {
    sizer.style.width = this.px(opt_maxWidth);
    //size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight);
 }

 // If the height is bigger than the max height then set the height and size
 // again
 if (opt_maxHeight && sizer.offsetHeight > opt_maxHeight) {
     sizer.style.height = this.px(opt_maxHeight);
     //size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight);
 }
 var size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight);

 document.body.removeChild(sizer);
 return size;
};
hrdwdmrbl
  • 4,814
  • 2
  • 32
  • 41

2 Answers2

2

The whole page may be being redrawn- Put the thing in an absolutly positioned, visibility hidden div element, it should be faster.

kennebec
  • 102,654
  • 32
  • 106
  • 127
  • I left it out because I didn't believe it to be relevant information, but before being insert, the element is style to be hidden and have absolute position. sizer.style.display = 'inline'; sizer.style.position = 'absolute'; sizer.style.visibility = 'hidden'; It's still really slow, especially since it happens a fair bit. – hrdwdmrbl Sep 01 '11 at 03:41
0

I think you can't do this with precision, because the true element size depends of its ancestor element.

Adilson de Almeida Jr
  • 2,761
  • 21
  • 37
  • Do you have any suggestions for how I might accomplish the same task, even without great precision? This code isn't actually my own, but is from a library I'm using. It's presently dragging my whole app down. If I can't find a solution I'll just need to ditch it altogether. Thanks for your help. – hrdwdmrbl Sep 01 '11 at 22:14