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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With