getBoundingClientRect() is returning zero in XUL

Andrei Sch. picture Andrei Sch. · Jan 2, 2011 · Viewed 9.9k times · Source

I have a problem with my firefox extension

I have a XUL popup panel with a hbox for the tag cloud, and a JS code to add divs to this hbox:

<hbox id="tag_base" ondblclick="alert('done')"/>

JS:

var root = document.getElementById('tag_base');
var tag = document.createElement('div');
tag.textContent = 'test';
root.appendChild(tag);
var rect = tag.getBoundingClientRect()
alert(rect.top)

I need to get the dimensions of each added div, however, getBoundingClientRect simply refuses to work. If I remove alerts, it's always zero. With alerts the story is different: The first time the alert is called it returns zero, although the div appears on the screen. Any subsequent alerts return the correct coordinates.

If I set a breakpoint in Chromebug, everything is reported correctly. If I do not interupt the execution in any way, and run a loop, only zeroes got returned.

This has got me quite confused. Calling "boxObject" produces the same results, while "getClientRects[0]" is undefined on the first call.

Any hints on what might be causing this will be greatly appreciated.

Answer

Mwea picture Mwea · Jan 17, 2013

Note : Caution, if you use getBoundingClientRect with an element which has display:none then it will return 0, anywhere in the dom.