If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Enjoy an ad free experience by logging in. Not a member yet? Register.

Looping, dimensions, and the DOM

I've got a function that picks a short phrase (a string) randomly from an array.
Let's say I'd like to display that phrase inside a div (#div1) of fixed width (960px). Within that div, I'd like the phrase to be placed at a random position.

(Edit: for aesthetic reasons, I'd like to keep the phrase all on one line.)

It's relatively easy to do that by randomizing some values, and appending the to that string to #div1 inside another div tag (#div2) with absolute positioning. Only problem is, I want the phrase #div2 to fit inside #div1... and since I don't know which phrase will be selected, I don't know the width of the #div2! So if #div2 ends up with a width of 200px and is placed at left:860px, it runs over by 100px.

Normally for these sorts of problems, I would use a while loop; ie: keep re-rolling until a value that does not run over is obtained. But a) I'm not so familiar with element dimension retrieval functions, and b) it seems like this could never work anyway, because once javascript rendered the new element in the DOM, (such that dimensions could be retrieved), the script would have already run and it would be 'too late'.

Thoughts on the matter? Is this problem solvable in js, or should I try a workaround?

div2.offsetWidth will let you know for example that left=860px is too far to the right for the div to fit the container.
you can always update the style after appending, it's never "too late" to re-position.