I have contenteditable
div
. Every time that content of div is changed, function to wrap each word with span
(for CSS) is called. I have 2 problems:
- After setting
innerHTML
, the cursor appears at the beginning of the div, I would like to cursor stay in the same position, - Newlines are deleted.
I tried to find a cursor positioning solution (eg. here) but I couldn't solve the problem with Range
or Selection
. Here is fiddle.
const div = document.querySelector('div')
div.addEventListener('input', () => {
let text = div.textContent
text = '<span>' + text.replace(/ /g, '</span> <span>').replace(/\n/g, '</span><br /><span>') + '</span>'
div.innerHTML = text
})
body {
background-color: white;
}
body > div {
background-color: black;
color: white;
font-family: Monospace;
padding: 0.5rem;
width: 20rem;
}
<div contenteditable="true">
Multiline text
<br />
Multiline
<br />
Text
</div>