I am using jQuery to do the following in one function:
initially I have a aboslutely positioned DIV; I set inner HTML of the DIV to some needed text/HTML; then I am showing the element at some certain coordinates using css({top: initialTop,left: initialLeft}).
Everything works fine inside the left and center area of the page - I see the DIV with topleft corner at the requested coordinates.
When I want to show the element on the right side of the page, I must keep the DIV 100% visible, so I have to show its topright corner at the requested coordinates (instead of topleft corner). I can get window width and scroll offsets without problems and I can calculate the offset to subtract from the topleft corner of the DIV to make its topright corner - I just take the DIVs width and subtract it form the coordinates.
The problem is - this approach works only the second time after I change the contents of the DIV. The first time I call myDiv.width(), it keeps the previous value - the width of the DIV with the old text. The second time I call the same function for the same element, everything works fine.
I have heard something about delayed rendering - it seems happening in my case; the browser is not rendering the DIV with updated text until the function exits, so I cannot get the right width.
Here goes the simplified code:
// at the beginning I have the following style:
#myDiv
{
position: absolute;
top: 0;
left: 0;
}
function PutDivWithInPlace(text, x)
{
var $div = $('#myDiv');
$div.html(text);
$div.show(); // even if it worked, I would really like to keep myDiv invisible to avoid it jumping from the old position to the new one
var width = $div.outerWidth();
// I ignore x-scroll offset here for simplicity
// if the right edge of div flows over the window right side, then push it to the left
if(x + width > $(window).width()){
x -= width;
}
$div.css({ left: x});
// this does not work - the width is still from the previous call of PutDivWithInPlace, so myDiv appears at the wrong place :(
}
Is there any other way to get the topright corner of the DIV where I need it to be in the same function where I change the contents of the DIV (but only if the DIV does overflow the window right side)? Maybe there is some other trick besides using DIVs width to get it right even after delayed render?