Created
February 5, 2014 18:54
-
-
Save hperrin/8830538 to your computer and use it in GitHub Desktop.
This function will give the Y position of the text cursor (caret) when it is in a contenteditable element. This particular one only works on CKEDITOR.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var getCaretYPosition = function(){ | |
var editor = CKEDITOR.instances.editor1, //get your CKEDITOR instance here | |
sel = editor.getSelection(), // text selection | |
obj = sel.getStartElement().$, // the element the selected text resides in | |
range = editor.getSelection().getRanges(), // range of selection | |
container = range[0].startContainer.$, // get the DOM node of the selected text, probably a textnode | |
textlen = typeof obj.textContent === "undefined" ? obj.innerText.length : obj.textContent.length, // get the length of the text in the container | |
offset = range[0].startOffset; // get the offset from the beginning of the text in the container to the caret | |
if (container.nodeType === 3) { // if the container is a text node | |
while (container.previousSibling) { // add the length of all the preceding text nodes and elements in the same parent element | |
container = container.previousSibling; | |
if (container.length) { | |
offset += container.length; // this is for text nodes | |
} else { | |
offset += container.textContent ? container.textContent.length : container.innerText.length; // this is for HTML elements | |
} | |
} | |
} | |
var pct = textlen > 0 ? offset / textlen : 0, // the percentage of the caret position | |
cursor = Math.floor(obj.offsetHeight * pct); // multiply elem height by percentage of carets position for caret's offset in pixels | |
while (obj.offsetParent) { // add all the offsets of all of its parents to get the complete offset of the caret from document origin | |
cursor += obj.offsetTop; | |
obj = obj.offsetParent; | |
} | |
cursor += obj.offsetTop; | |
return cursor; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Brilliant !
This is far better than this other method i saw : insert a empty "fake" element, get cursor position (i.e. fake elt position), then remove the fake element.
Thus, like the other method, there is some problem with selecting text with keyboard (shift+arrows) :
The correct Y position is achived only when selecting UP.
When selecting DOWN the top postion of selection is given (instead of the bottom wich would be better)
Also : selecting over blank lines make gives false cursor position
Would you know how to make it work ?