Pregunta

I try to find the caret position in an editable div. Also it should be nice to get the selected text in this div.

I try to assimilate this: Editable Div Caret Position

But it dosen’t work.

I'll be happy to give any Idea.

Thanks in advance

Some code snippet

HTML

<a on-click="{{chooseMenu}}" which-menu="1">Menu 1</a>

Dart

  void chooseMenu(Event event, var detail, var target) {

    event.preventDefault();
    event.stopPropagation();

    Selection sel;
    Range range;

    sel = window.getSelection();

    if(sel != null) {
      range = sel.getRangeAt(0);
      range.collapse(false);
    }

    currentSubMenu = int.parse(target.attributes['which-menu']);
  }
¿Fue útil?

Solución

This worked for me in Dartium.

The other code from the referenced SO question is probably to support other browsers. Dart usually generates JS code that works in all supported browsers. You have to test yourself if the generated JS really works in the browsers you want to support.

EDIT

We store the selection whenever it changes. Maybe there are better events but I couldn't find one. But it worked fine for me. We insert the new node at the previously stored selection.

// must be accessible by getRange, insertNodeAfterSelection 
DivElement editable;
Range range;

// store reference to our contenteditable element
editable = (document.querySelector('#editable') as DivElement);

// subscribe selection change events
document.onSelectionChange.listen(getRange);


void insertNodeAfterSelection(Node node) {
  range.collapse(false);
  range.insertNode(node);
}

void getRange(Event e) {
  if(document.activeElement != editable) { // save only selection changes on our contenteditable
    return;
  }
  print(e);
  Selection sel;

  sel = window.getSelection();
  if(sel != null) {
    range = sel.getRangeAt(0);
  }
}

You have to decide yourself where you put those code parts. I added some comments as support.

EDIT
using the mousedown event instead of click should help around this issue
Preserve text selection in contenteditable while interacting with jQuery UI Dialog and text input

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top