HTML:
<h1 placeholder="Text Here" contenteditable="true"></h1>
CSS:
h1 {
border: 1px black solid;
outline: none;
text-indent: 36px;
}
h1:empty::before {
content: attr(placeholder);
color: grey;
}
JS:
const h1 = document.querySelector('h1');
h1.addEventListener('input', () => {
if (h1.textContent !== '') return;
let elemToDel = [];
for (let i of h1.children) {
elemToDel.push(i);
}
elemToDel.forEach(i => i.remove());
});
https://jsfiddle.net/5fnvztsg/
The JS code is there to remove remaining newlines when h1.textContent is empty, so that :empty::before gets applied.
However, pressing enter when there is no text present (except for the ::before) causes the caret to seemingly ignore the text-indent, though typing anything then pressing enter, then deleting the newline and typed text seems to put it in the right place again.
I wrote this:
const caretPos = window.getSelection();
const range = document.createRange();
range.selectNodeContents(h1);
range.collapse(false);
caretPos.removeAllRanges();
caretPos.addRange(range);
right after “elemToDel.forEach(i => i.remove());” but it didn’t seem to work.
I also tried:
h1.textContent = ' ';
after “elemToDel.forEach(i => i.remove());” which fixed the caret issue, but at the cost of removing the ::before.