5

So, I have a contenteditable div powered by Facebook's draft-js. I needed to get the visual position of the caret inside that div, and I implemented this (which works in Firefox and Chrome):

const selection = window.getSelection && window.getSelection();
if (selection.rangeCount > 0) {
    const coordinates = selection.getRangeAt(0).getBoundingClientRect();
}

I get the correct coordinates in case of Chrome and Firefox. However, in Firefox, I am getting 0 for all the position properties. Any workaround/cross-browser solution for this?

Tarun Dugar
  • 8,921
  • 8
  • 42
  • 79

1 Answers1

3

Seems like I've fixed the issues using next code:

let range = window.getSelection().getRangeAt(0);
range = range.cloneRange();
range.setStart(range.startContainer, 0);
range.getBoundingClientRect();

Here is the fiddle.

UPDATE 13 Feb 2020:

Here is updated fiddle with fixed caret position for very first line when input is multiline.

  • Could you point to where you found this or why it works? I would like to understand why this happens only in Safari. – ragurney Jan 28 '20 at 18:06
  • @ragurney I don't exactly remember how I found a solution, it was long time ago... And now it seems like it works without my code above. Both in Safari and Chrome. But I fixed bug for the very first line with multiline text. (caret was below whole input, now it works correct) – Evgeniy Viniychuk Feb 13 '20 at 08:34