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
}
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.
const editor = document.getElementById("editor")
editor.addEventListener("keyup", () => console.log(checkLine()))
function checkLine() {
// get last div
const last = editor.querySelector("div:last-of-type")
// 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
}
/* css just for the demo */
#editor { outline: none; }
#editor:empty::before {
content: "Start typing...";
pointer-events: none;
color: #bbbbbb;
}
<div id="editor" contenteditable></div>