How to check if caret is at the end of contenteditable div?

3.4k views Asked by At

There are a lot of questions here how to set the caret at the end of a contenteditable div, but I would like to know how to check if the caret/cursor is at the end.

Currently I do the following test:

var lengthEditor = editor.text().length;
var range = window.getSelection().getRangeAt(0);
var pRange = range.cloneRange();

pRange.selectNodeContents(editor.get(0));

var start = pRange.setEnd(range.startContainer, range.startOffset).toString().length;

if(start == lengthEditor) {
 //do something
}

Most of the time this is alright, but there will be instances where it's not equal even though I'm sure the caret is at the end. Is there another way to check if the cursor is at the end of the contenteditable div?

Also, I'd like to point out that the contenteditable div may contain multiple span elements.

0

There are 0 answers