JSFiddle - React, Tailwind, and code Playground
HTML
<h2>Selection and focus</h2>
<input id=i value="foo">
<div contentEditable=true>Editable</div>
<button type=button>Update</button>
<button type=button>Focus</button>
<button type=button>Focus-Blur</button>
<pre id="console1"></pre>
<pre id=console></pre>
CSS
pre {
color: #888;
white-space: pre-wrap;
}
JavaScript
function log(str) {
document.getElementById('console1').textContent += str + '\n';
}
setInterval(function() {
var i = document.getElementById('i');
var s = window.getSelection();
document.getElementById('console').innerHTML = 'start=' + i.selectionStart +
' end=' + i.selectionEnd +
'\nselection=[a:' + s.anchorNode +
',' + s.anchorOffset +
' f:' + s.focusNode +
',' + s.focusOffset +
' s="' + window.getSelection().toString() +
'"]';
}, 333);
document.querySelector('button').addEventListener('click', function() {
document.getElementById('i').value = 'foo';
}, false);
document.querySelectorAll('button')[1].addEventListener('click', function() {
document.getElementById('i').focus();
}, false);
document.querySelectorAll('button')[2].addEventListener('click', function() {
var i = document.getElementById('i');
i.focus();
i.select();
//i.style.display = 'none';
setTimeout(function() {
i.blur();
//i.style.display = 'inline-block';
}, 2000);
}, false);
var i2 = document.createElement('input');
log('Initial: ' + i2.selectionStart + '-' + i2.selectionEnd);
i2.selectionStart = 3; i2.selectionEnd = 5;
log('Set 3-5: ' + i2.selectionStart + '-' + i2.selectionEnd);
i2.value = 'foom';
log('Set foom: ' + i2.selectionStart + '-' + i2.selectionEnd);