Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getBoundingClientRect return 0 for top, left, right, bottom in Safari

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?

like image 753
Tarun Dugar Avatar asked Oct 18 '22 21:10

Tarun Dugar


1 Answers

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.

like image 100
Evgeniy Viniychuk Avatar answered Oct 23 '22 03:10

Evgeniy Viniychuk