How to get the cursor position in TinyMCE or the number of line on which the cursor is in TinyMCE?
Asked
Active
Viewed 2,333 times
1 Answers
2
Here is the part of a function from one of my own plugins i use to get the actual line number:
var ed = tinymce.get('my_editor_id');
var bm = ed.selection.getBookmark();
var $marker = $(ed.getBody()).find('#'+bm.id);
var elem = ed.getDoc().getElementById(bm.id+'_start');
try {
box = elem.getBoundingClientRect();
}
catch(e)
{
// should not happen
console.log('error creating box: ' + e);
}
var doc = ed.getDoc(),
docElem = doc.documentElement,
body = ed.getBody(),
win = ed.getWin(),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
// set Bookmark
ed.selection.moveToBookmark(bm);
var caret_line = Math.floor( (top) / lineHeight ) + 1;
The function getBoundingClientRect()
is used to create a box from which we can get several positioning information. Be aware the we need to use a marker-element and reset the caret later on.
Update: Info for lineHeight
// get height of row: eighter line-height or min-height
if ( $(ed.getBody()).find('p:first').css('line-height') != 'normal'){
lineHeight = $(ed.getBody()).find('p:first').css('line-height') ;
}
else {
lineHeight = $(ed.getBody()).find('p:first').css('min-height');
}
var lineHeight = lineHeight.substr(0, lineHeight.length -2 );

Thariama
- 50,002
- 13
- 138
- 166
-
Can you see this question: http://stackoverflow.com/questions/11881262/two-divs-one-with-tinymce-to-share-a-scrollbar – petko_stankoski Aug 09 '12 at 10:25
-
what is lineHeight in your piece of code please? you don't have it defined anywhere. Thanks :) – Bernice Mar 19 '13 at 13:45
-
see my updated answer, in our use-case we have a defined heigth for all paragraphs in the editor – Thariama Mar 19 '13 at 15:38
-
oh I see so you gave a height for each of your paragraphs! Thanks for your help :) trying to use this together with the anchor offset maybe I can find the position for a caret.. – Bernice Mar 20 '13 at 08:28
-
this is not working for me, linHeight ended up being 0 and then dividing by it gives infinity. http://paste.ubuntu.com/15189004/ – Charbel Feb 24 '16 at 17:34