How can I check if the text cursor is inside of a contenteditable div?

Viewed 716

I'm using a rich text editor called Quill which generates a contenteditable div like this:

<div class="ql-editor" data-gramm="false" contenteditable="true">
</div>

Of course, that div then contains HTML for whatever content is currently in the editor. The HTML is often nested.

Is there a slick way of easily determining if the text cursor (caret) is currently within a contenteditable div? If not, what's the best way to check if the text cursor is within a contenteditable div or a child node of a contenteditable div?

I'm using vanilla JavaScript.

3 Answers

Just use document.activeElement and Element.closest API.

const activeDiv = document.activeElement.closest('[contenteditable]');

function onMouseUp(e) {
  const activeDiv = document.activeElement.closest('[contenteditable]');
  
  console.log(activeDiv);
  

  const outputElement = document.getElementById('output-element');
  outputElement.innerText = activeDiv.id;
}

const textarea1 = document.getElementById('ta-example-one');
const textarea2 = document.getElementById('ta-example-two');
textarea1.addEventListener('mouseup', onMouseUp, false);
textarea2.addEventListener('mouseup', onMouseUp, false);
<form>
<div id="ta-example-one" data-gramm="false" contenteditable="true">
Foo bar baz plugh
</div>
<div id="ta-example-two" data-gramm="false" contenteditable="true">
Foo bar baz plugh
</div>
</form>

<p>Active element ID: <strong id="output-element"></strong></p>

Okay ,so I tried something different. It seem you want to know if that div has focus. (For example if your div was input element and you want to know if is currently focused).

Try this.

let textDiv =document.getElementById('textDiv');
   testDiv.addEventListener('focus',function(){
   if(testDiv.focus){
      console.log('coursor inside!')
   }
})

Maybe it will work

I don’t know If I get your question right. If you want to know If the coursor is inside that div solution may be onmouseover event.

<div class="ql-editor" data-gramm="false" contenteditable="true" onmouseover= "isInside()">
function isInside(){
  Console.log("Coursor is inside!")
} 

Or you can do it all in Javascript ,but you have to add ID to that div. For example div will be : textDiv.

Let textDiv = document.getElementById("textDiv");
textDiv.addEventListener("mouseover",function(){
    Console.log("Coursor is inside !");
});
Related