1

Let's say I have a very long paragraph. When I click on a line, JS/jQuery will add an empty <span> tag at the beginning of this specific line - right before the first word in this line.

f.e: This is my paragraph:

<p>
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has.
</p>

When I click the second line, a <span> tag will be insert before the first word in the second line.

Any ideas how to do it?

JJJ
  • 32,902
  • 20
  • 89
  • 102
dsternlicht
  • 78
  • 10

2 Answers2

2

jQuery can't detect where a wrapped line occurs, unless it happens with a hard-coded break (<br /> or similar).

That said, there is one option, although it's a little hacky.

  1. Duplicate the container
  2. Give it a left of -3000 (to make it invisible, without using display:none because that gives it 0 height)
  3. Remove one word at a time (using .lastIndexOf(' ')), and measure the height each time. When it resizes to the smallest non-zero height, that's where you want to insert your <span>, so then...
  4. .substring() with the position you've just found - .substring(0, position) + '<span>' + .substring(position)
Joe
  • 15,669
  • 4
  • 48
  • 83
  • Nice idea, thanks. But what about performance? Consider that paragraph can be very long, if I'll need to pass each word in the paragraph on each click the user fired it's could be heavy.. – dsternlicht Feb 22 '12 at 12:20
  • @fastrd Compare the `.length` of the `p` first, to see if it's changed - if not there's no sense in re-running it. You could also go from the front of the para, putting the words into a new para and look to see when it grows (which will indicate your new line). That way you're only ever going over the first line. Clone the original, blank its content and send it off-screen, then add words from the original para. – Joe Feb 22 '12 at 12:24
1

Hello Friend You can find the possible duplicate here in the following link

Get caret position in contentEditable div

Hope this solves your problem.

Community
  • 1
  • 1
AmGates
  • 2,127
  • 16
  • 29