I've been searching a lot but i could't find a way to get (X,Y) coordinates for the caret on a content editable div,there's a lot of content on the web about this,but the problem none of the pages i found get the coordinates according to the top of the div,so my question in a simpler way is:
How can i get the (X,Y) coordinates of the caret on a contenteditable div,but the Y coordinate must be calculated according to the top of the div and not from the top of the visible part of the page?
Note 1: I need specially the Y coordinate.
Note 2: I can only use pure javascript,no JQUERY.
My way:
I haven't found a direct way to do this,so as a workaround i thought on getting the Y coordinate according to the visible part of the page and the hidden part of the Div and sum the results(I'm currently working on this but i getting no luck!).
The CaretPosition interface represents the caret position, an indicator for the text insertion point. You can get a CaretPosition using the Document.
Definition and Usage The contenteditable attribute specifies whether the content of an element is editable or not.
To move the cursor to the end of an input field: Use the setSelectionRange() method to set the current text selection position to the end of the input field. Call the focus() method on the input element. The focus method will move the cursor to the end of the input element's value.
Answer: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.
get selection and range
var sel = window.getSelection();
var range = sel.getRangeAt(0);
insert collapsed div
var div = document.createElement(...)
range.insertNode(div)
get div coordinates
try this:
var selection = window.getSelection(),
range = selection.getRangeAt(0),
rect = range.getClientRects()[0];
in the rect var you should find the position:
rect.left
-> for the x coordinate
rect.top
-> for the y coordinate
there is also rect.width
and rect.height
. In case the user has some text selected rect.width
will be >0.
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