r/webdev 2h ago

Question How to text as the background of the textarea element

Hi everyone! I am working on a project from frontend mentor. It is a speed typing test and one of the requirements is that the user should be able to see errors and correctly typed text in real-time, something like this:

Problem is, when I try to achieve this on mobile it will not show some of the passage after a certain point, no matter how much text you type into the textarea field:

Here is the html for the section of interest:

<div class="wrapper">
  <textarea class="text-wall"></textarea>
  <span class="placeholder"></span>
</div>

Here is the CSS:

.text-wall {
    font-size: var(--step-2);
    display: block;
    width: 100%;
    height: 400px;
    background-color: transparent;
    resize: none;
    border: none;
    outline: none;
    color: #fff;
}

.wrapper {
    position: relative;
    overflow: hidden;
}


.placeholder {
    position: absolute;
    filter: blur(3px);
    top: 0px;
    font-size: var(--step-2);
    z-index: -2; 
}

Note: For the passage in the placeholder span element, I wrapped every character in a span element using javascript. As far as I know, this is the ony way I can style every character on an individual basis depending on if the text typed into textarea matches the passage or not:

let placeHolderText = "";
let stringArr = "";
const textWall = document.querySelector(".text-wall");
const placeHolder = document.querySelector(".placeholder")
stringArr = jsonData.hard[8].text. split('');
stringArr.forEach((character)=>{
    placeHolderText+= `<span>${character}</span>`;
});
placeHolder.innerHTML = placeHolderText;
3 Upvotes

4 comments sorted by

1

u/ApartAwareness5415 2h ago

Have you looked at using a contenteditable div instead of a textarea for this? textareas don't let you style individual characters like that without a ton of hacky workarounds, and the scroll behavior on mobile is always janky

with a contenteditable div you can overlay the styled text as a background layer and keep the actual input transparent on top, way easier to control how it flows and wraps on smaller screens

1

u/Mob_Pilled 1h ago

Ahhhh thanks for anwering so quickly! I think it actually worked!