I am trying to create a text box that allows users to type. As they do, the most recent (last) words will be black and the previous ones fade to white.
Right now, I have a contenteditable with the following code. Whenever there is a change it takes the current text, splits it into words, wraps the last few words in a span with a black text color class and the previous ones in a span with a white text color class (and some fade between colors). It works, but doesn’t allow for new lines nor any formatting (bold/italics/underline). Is there a way to do this that still allows those? I’ve tried looking at other customizable rich text editors like quill but couldn’t figure out how to get the fade effect. I don’t need most of the functionalities of these rich text editors, really only bolding/italics/maybe font size.
editor.setAttribute("data-placeholder", getRandomPlaceholder(placeholderTexts));
// get rid of spell check red squiggles
editor.spellcheck = false;
editor.focus();
editor.blur();
editor.addEventListener('input', () => {
let words = editor.innerText.split(/s+/);
let blackWords = words.slice(-3);
let fadeWords = words.slice(-8, -3);
let whiteWords = words.slice(0, -8);
let whiteSpan = document.createElement('span');
whiteSpan.className = 'white';
whiteSpan.innerText = whiteWords.join(' ');
// Create fade spans
let fadeSpans = fadeWords.map((word, index) => {
let span = document.createElement('span');
span.className = `fade-${index + 1}`;
span.innerText = word;
return span;
});
let blackSpan = document.createElement('span');
blackSpan.className = 'black';
blackSpan.innerText = blackWords.join(' ');
editor.innerHTML = '';
if (whiteWords.length > 0) {
editor.appendChild(whiteSpan);
editor.appendChild(document.createTextNode(' '));
}
// Append fade spans
fadeSpans.forEach((span, index) => {
editor.appendChild(span);
if (index < fadeSpans.length - 1) {
editor.appendChild(document.createTextNode(' '));
}
});
if (fadeWords.length > 0) {
editor.appendChild(document.createTextNode(' '));
}
editor.appendChild(blackSpan);
// Move cursor to the end
let range = document.createRange();
let selection = window.getSelection();
range.selectNodeContents(editor);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
});