-1

I have a contenteditable div and I need to show a custom element at the cursor position whenever a user types a certain character.

To do this, I need to know where the cursor (not the mouse - the vertical line that letters come out of) is located whenever this happens. How can I do this?

BLAZORLOVER
  • 1,971
  • 2
  • 17
  • 27
  • Related: [get and set cursor position in content editable div](https://stackoverflow.com/questions/59894560/get-and-set-cursor-position-in-content-editable-div) – Tân Apr 15 '20 at 01:38
  • @Tân how would I display a div at an *index* (as opposed to coordinates)? – BLAZORLOVER Apr 15 '20 at 01:43
  • You can use it within keyboard events: *input, keypress, keydown....*. You can generate your custom div element and append it based on the cursor position – Tân Apr 15 '20 at 01:47
  • @Tân again... how can we extrapolate x/y coordinates for a div (that needs to be positioned with x/y coordinates) from cursor position? – BLAZORLOVER Apr 15 '20 at 01:50

1 Answers1

0

If I understand you mean correctly, you may want to insert some div element into [contenteditable] element based on cursor position.

If true, you can try this way:

function append(node) {
  var sel = window.getSelection();
  var range = sel.getRangeAt(0);
  range.deleteContents();
  range.insertNode(node);
}

add.addEventListener('click', function () {
  var node = document.createElement('div');
  node.innerText = 'foo';
  node.className = 'test';
  
  append(node);
});
[contenteditable] {
  border: 1px solid #ccc;
}

.test {
  color: #f00;
  display: inline-block;
}
<div contenteditable>Hello world!</div>
<button type="button" id="add">Append text</button>

In this example, you can click on the editor to set cursor position, then clicking on the button to append new div tag.


You can also use this way to append some div tag via input or keypress or keydown... events by detecting character, such as: @ #

Tân
  • 1
  • 15
  • 56
  • 102