0

I'm trying to accomplish something I believe should be simple to do in jQuery.

I have a long text in my website. Whenever a user selects (highlights) a text, I need to get the following info:

  • The paragraph where the selection begins at
  • The char in that paragraph that the selection starts at
  • The length of the selection
  • The paragraph where the selection ends at (in case the highlight goes beyond one paragraph)
  • The char in that paragraph where the selection ends

Thanks ahead ;)

Jens Roland
  • 27,450
  • 14
  • 82
  • 104
Skipper Geffen
  • 75
  • 2
  • 11

3 Answers3

1

You need to use JavaScript for anything that deals with text selections. jQuery has no built in function for detecting where a selection begins or where it ends. Rangy http://code.google.com/p/rangy/ could be something you can use for such purpose.

Hussein
  • 42,480
  • 25
  • 113
  • 143
1

I think I've answered all of these on Stack Overflow before. In turn:

  • A combination of getAncestor() from here and getSelectionBoundaryContainerElement() from here will do the job
  • It depends what you mean by "char in that paragraph that the selection starts at". If the paragraph may have other elements inside rather than just one text node, this becomes slightly tricky. You could adapt this.
  • Again, this depends on what you mean by the "length of the selection". You could get the selected text as a string and use its length property.
  • See answers for selection start
  • See answers for selection start

You'll need to do a little study of the APIs to do this, which is no bad thing.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

play around with

window.getSelection
document.getSelection
document.selection.createRange()

See an example on this site: http://www.codetoad.com/javascript_get_selected_text.asp

Mike
  • 367
  • 4
  • 8