views:

224

answers:

1

I want to insert an image tag into a block of text so that the image is, say, 100 pixels down in the DIV.

    <div>
    A lot of text in a text block and a <img tag> somewhere
that is floated left or right and positioned inside the text block
    </div>

So, the tag above is put in the text block to be floated so that it is positioned at 100px DOWN in the DIV. Now, this can't be done statically, it has to be done in javascript since 100px down in the div may be represented by different text depending on font rendering issues and such.

So, is there a way to find what "word" in a text block that is 100px down in the DIV? jQuery perhaps?

+2  A: 

The short answer is no

Basically it comes down to the DOM doesn't give a way for you to get an elements pixel position. There are sort of hacks you can do for some browsers, but good luck getting a solution working.

If you cannot get the position of the containing div, you are not going to get the position for the text within.

Leaving aside the no, if you were to find a way to get the div's pixel height, I would follow a procedure similar to the following.

  1. Get the text from inside the div and store it in a local var.
    1. Inside a loop for each word in the text:
    2. Insert a div tag into just before the word.
    3. Get the pixel position of the div tag.
    4. Use this to determine the closest word to pixel pos 100 down.
  2. Once you have the closest position, create a document fragment to build up your new inner for the div
  3. Replace the div's content with the document fragment.
Dan McGrath
sort and sweet :D lol
Rakesh Juyal
Sorry, I just ruined that :( haha
Dan McGrath
That's a pretty nifty solution. I have to test it to see how it works speed-wise, sounds like it could be pretty cpu consuming
Sandman
Thanks. Each loop will cause a reflow. If you have a lot of words, that is a lot of work.
Dan McGrath
Just a thought. Using the concept of binary search, you can greatly reduce the amount of reflows and position checks you need to do.
Dan McGrath
Hmmm, "binary search"?
Sandman
I get it now. I rather think that I should compute the line-height, font-size and then the width of the container to find the *probable* position of the insertion, and positioning it there, and then move it one word back/forward until it is perfect.
Sandman