Issue with getBoundingClientRect in contenteditable div when caret is inside an empty child div

30 views Asked by At

I have a contenteditable div with a selectionchange event that logs the new range's getBoundingClientRect. Everything works well until the caret is moved inside an empty div, like this:

 <div contenteditable="">
        bbackground: transparent !important;
        <div id="meyes" style="padding-left: 100; min-height:1em;width: 500px;background-color: bisque;text-align: center;"></div>
        text
    </div>

  document.addEventListener('selectionchange', (e) => {
        let sel = window.getSelection();
        if (sel.rangeCount > 0) {
            let range = sel.getRangeAt(0).cloneRange();
            const rect = range.getBoundingClientRect();
            console.log("rect", rect);
        }
});

In this scenario, when the caret is inside the empty div with id 'meyes,' the getBoundingClientRect returns all zeros: {x: 0, y: 0, width: 0, height: 0}. Is there a way to resolve this issue or work around it to obtain the actual getBoundingClientRect even in an empty div?"

Any alternative suggestions would be greatly appreciated.

1

There are 1 answers

0
ControlAltDel On

You are getting this because your selection is empty. Were you expecting this to respond the size of the full element, even though no text in it is selected?

setTimeout(function() {
  var r = document.querySelector("div").getBoundingClientRect();
  console.log(JSON.stringify(r));
  var r2 = window.getSelection().getRangeAt(0).getBoundingClientRect();
  console.log(JSON.stringify(r2));

}, 3000);
div {
  width: 300px;
  min-height: 30px;
  background: orange;
}
<div contenteditable="true">
</div>