Annotating or grabbing highlighted text

I want the user to highlight text within a rich text control and be able to:

  1. get the text (or ideally location in text) that was highlighted.
  2. Trigger an event based on this occurring.

The purpose for this is annotation. I believe this will need to use javascript but I was wondering if anyone had done something similar who could point me in the right direction?

My use case is to annotate text that will get fed into a ML model.

Hello @james2 . Was this question ever answered? I am looking for the same thing.

In a TextArea I set the placeholder property to "type something here", then I define these two javascript functions:

  function getSelectionPosition(placeHolderText) {
    element = $('[placeholder="' + placeHolderText + '"]');
    return [element.prop("selectionStart"), element.prop("selectionEnd")];
  }

  function setSelectionPosition(placeHolderText, selStart, selEnd) {
    element = $('[placeholder="' + placeHolderText + '"]');
    element.prop("selectionStart", selStart);
    element.prop("selectionEnd", selEnd);
  }

and use them like this:

# get the current selection
sel_start, sel_end = self.call_js('getSelectionPosition', 'type something here')

# set the selection
self.call_js('setSelectionPosition', 'type something here', sel_start, sel_end)

I have not tried with RichText, you may need to do some work to account for the formatting characters.


PS1
This is 5 year old code and today there may be a better way to interact with the DOM, but it’s simple enough and it still works on my apps.

PS2
This only works if the placeholder is unique across all the elements in the form.