Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get caret coordinates on a contenteditable div through javascript.

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!).

like image 532
Mateus Avatar asked Jun 10 '13 03:06

Mateus


People also ask

What is caret position in Javascript?

The CaretPosition interface represents the caret position, an indicator for the text insertion point. You can get a CaretPosition using the Document.

What is Contenteditable div?

Definition and Usage The contenteditable attribute specifies whether the content of an element is editable or not.

How do I set the cursor position in input?

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.

How do you make a div Contenteditable?

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.


2 Answers

  1. get selection and range

     var sel = window.getSelection();
     var range = sel.getRangeAt(0);
    
  2. insert collapsed div

     var div = document.createElement(...)
     range.insertNode(div)
    
  3. get div coordinates

  4. remove the div
like image 194
Edgar Abgaryan Avatar answered Sep 21 '22 19:09

Edgar Abgaryan


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.

like image 44
Oliver Wolf Avatar answered Sep 22 '22 19:09

Oliver Wolf