contenteditable - caret r&d

by tnhu

HTML

<input>
<p></p>

<div id="fake1" contenteditable="true" class="single-line"><span></span><span>|</span></div>
<p></p>

<textarea></textarea>
<p></p>

<div id="fake2" contenteditable="true">
  <span>|</span>
</div>

CSS

[contenteditable="true"].single-line {
    white-space: nowrap;
    width:400px;
    overflow: hidden;
} 
[contenteditable="true"].single-line br {
    display:none;

}
[contenteditable="true"].single-line * {
    display:inline;
    white-space:nowrap;
}

input,
#fake1 {
  display: block;
  width: 400px;
  height: 16px;
  white-space: nowrap;
  font-size: 16px;
  padding: 8px 20px;
  margin: 0;
  font: 400 16px system-ui;
}

textarea,
#fake2 {
  display: block;
  width: 200px;
  height: 100px;
  overflow: auto;
}

JavaScript

var input = document.querySelector('input');
const fake1 =   document.querySelector('#fake1')
var span = document.body.appendChild(document.createElement('span'))

fake1.addEventListener('keydown', e => {
  var rect = window.getSelection().getRangeAt(0).getBoundingClientRect()
	input.value = JSON.stringify(rect) + ' : scrollLeft: '+ fake1.scrollLeft
  
   span.style.top = rect.top + 'px'
   span.style.left = rect.left + 'px'
})


span.style.cssText = 'position: absolute; display: inline-block; margin: 0; padding: 0; height: 18px; width: 2px; background: red; z-index: 99999;';