I am working on my javascript to check the cursor position in the contenteditable to see if the cursor is on the last line then return the boolean as true, otherwise false.
When I try this:
function checkLine() {
var myElement = document.getElementById('editor');
var startPosition = myElement.selectionStart;
var endPosition = myElement.selectionEnd;
var endofLine = false;
if(startPosition == endPosition){
endofLine = true;
}
return endofLine;
}
It is always return as true when I selected the cursor on the first line, second, third and forth lines in the contenteditable without the last line, it should have return as false when the cursor is not on the last line.
What I am trying to achieve is when I select on the first, second, third and forth lines in the contenteditable, I want the boolean to return as false and when I select the cursor on the last line, I want the boolean to return as true.
Can you please show me an example how I can check the cursor in the contenteditable that if they are on the end line then return the boolean as true otherwise false?
EDIT: Could you please clear up the code a bit and use something like this?
function checkLine() {
// get last div
const last = $('#editor').querySelector(":last-of-type");
var endofLine = false;
// if there is no div, that means there's only one line
if (!last) {
return true;
}
const sel = window.getSelection();
let parent = sel.getRangeAt(0).commonAncestorContainer;
if (parent.nodeType !== 1) {
parent = parent.parentNode;
}
return parent === last
}
3
Answers
Sorry for the delay, I edited my code to be working with
contenteditable Div
:We can take advantage of the fact that with contenteditable divs, when a user enters a new line, a new div is automatically created for that line. This way, we can query the last div of the contenteditable and see if the cursor is in it.
When the user makes a line break in a
contenteditable
tag that string is wrapped in a<div>
. In the example below when triggered by a "click" or "keydown" event on the<fieldset contenteditable>
it will:<div>
into an Array<div>
the user clicked on or typing into