0

I recently came across an odd behavior when trying to calculate the width (with margins) of an element using gwtQuery. The goal is to get the width (including padding, borders and margins) of a given element as a child of a certain parent. This parent may define specific CSS rules for some children so I clone it, add my element to this parent, call .outerWidth(true) to get the width and finally remove the clone from the parent.

It works fine on Chrome, Firefox and IE 10, but randomly fails (outputs 0) on IE 8. However I noticed that if I put a "sleep" between the moment I add the element to the DOM and the moment I get the outer width, it always succeeds.

I obviously don't want to keep that sleep. So my question is does anyone has any insights on how to work around this behavior or even a better way of achieving the same goal?

Thank you!

Here's a code snippet

private Integer computeTabWidth(IsWidget tab) {
    GQuery $tab = $("<li></li>").append($(tab).clone());

    $(containerPanel).append($tab);

    // IE 8 debug.
    sleep(100);

    Integer tabWidth = $tab.outerWidth(true);
    $tab.remove();

    return tabWidth;
}

private void sleep(int i) {
    long time = new Date().getTime() + i;

    while (time > new Date().getTime());
}
Chris
  • 165
  • 1
  • 5
  • Maybe you could calculate the width asynchronously, only when the element is attached to the DOM (using AttachEvent). I'm thinking IE8 might be slow to update its DOM. – spg Nov 12 '13 at 14:19

1 Answers1

1

I think it is a reflow issue, try forcing the browser to make a reflow before reading it, replace your sleep approach with:

$tab.css("offsetHeight")
Manolo Carrasco Moñino
  • 9,723
  • 1
  • 22
  • 27
  • That didn't work but I was using IE 11 on compatibility mode to test with IE 8. I decided to install a VM with a real IE 8 and I can't reproduce the issue. It looks like compatibility mode has its own set of issues. I will upvote because I think you answer may still be useful to others. – Chris Nov 14 '13 at 17:40
  • Yep, compatibility is not the ideal thing for testing old browsers. Maybe setting some styles could make it work, but not sure. – Manolo Carrasco Moñino Nov 14 '13 at 18:12