What is the best way to ensure that my placeholder text remains permanent and properly formatted?

Looking to create a basic typing test app using HTML, CSS and JS. My goal is to have placeholder text displayed in the input box so users know what to type as they type. Misalignments between the placeholder text and user input will indicate mistakes. After hours of trial and error, I've developed two subpar solutions:

    <div id='test' class="placeholder" data-value="This appears in the box!">
    <textarea id="typed" name="typed" cols=50 rows=15></div>

CSS:

    .placeholder
    {
        position: relative;
    }

    .placeholder::after
    {
        position: absolute;
        left: 2px;
        top: 2px;
        content: attr(data-value);
        pointer-events: none;
        opacity: 0.6;
        text-align: left;
    }

While this method works well, it struggles with handling newlines properly. Various attempts like \u000A, \x0A, \r\n haven't yielded success.

Option two involves utilizing the placeholder attribute:

    <textarea placeholder="line1
    line2" id="typed" name="typed" cols=50 rows=15></textarea>

This approach displays the text correctly but it disappears when users begin typing.

Anyone aware of how to keep standard placeholder text visible permanently or any other workaround for correct formatting?

Answer №1

Instead of resorting to data attributes or placeholder text for this task, I recommend avoiding them altogether. Implementing line breaks and ensuring cross-browser compatibility may prove challenging if you take that approach. Have you considered using two absolutely positioned textareas stacked on top of each other? The lower textarea can contain the required user input text and remain disabled, while the upper one could have a transparent background, allowing the text below to be visible. Below is a simple concept of how this setup could appear:

textarea {
  position: absolute;
  font-size: 20px;
}

#type {
  color: red;
}

#typed {
  background: none;
  z-index: 10;
}
<div id='test' class="placeholder">
  <textarea id="typed" name="typed" cols=50 rows=15></textarea>
  <textarea id="type" name="typed" cols=50 rows=15 disabled>
    This is the text you need to type.
    You can include as many lines as necessary.
  </textarea>
</div>

JSFiddle

Answer №2

Check out this example.

You were almost there! I simply grouped them together in a container.

The div and text textarea are positioned absolutely and share the same font properties. The placeholder is adjusted to accommodate the 1px border and 2px padding on a textarea. These are default values, so if you modify them, be sure to update the placeholder positioning accordingly.

.container {
    position: relative;
}
textarea
{
    position: absolute;
    top: 0px;
    left: 0px;
}

.placeholder
{
    position: absolute;
    left: 3px;
    top: 3px;
    content: attr(data-value);
    pointer-events: none;
    z-index: 1;
    opacity: 0.6;
    text-align: left;
}

textarea,
.placeholder {
    font-family: arial;
    font-size: 16px;
}

As you can see below, the placeholder div includes a line break with <br />. Keep in mind that HTML handles line breaks differently than plain text, so make adjustments in your comparison code:

<div class='container'>
    <div id='test' class="placeholder">This text appears<br /> in the box</div>
    <textarea id="typed" name="typed" cols=50 rows=15></textarea>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to find component: "wrestler-choice-box". If this is a built-in custom element, please ensure it is not included in component resolution

In my attempt to achieve a specific goal, I have an array of data that I want to incorporate into my HTML document along with a Vue component containing a template. My intention is to utilize list rendering so that the names and images from this array bind ...

The duration of recorded audio in JavaScript is unclear

I managed to successfully create a structure for recording and downloading audio files. However, I'm facing an issue where the final downloaded file has an unknown duration. Is there any way to solve this problem?? Here is my Typescript code snippet: ...

Ensuring Form Validation in Symfony 2.0 View

I am currently using Symfony 2.0 and I have a view file called test.html.php which includes a form: <form action="" method="post" rel=""> <input type="hidden" name="action" value="test" /> <input name="myinput" type="text" value="" ...

Is the NPM package not being imported? How exactly is it being utilized?

mediacms-vjs-plugin is a unique plugin designed for Video.js. The MediaCmsVjsPlugin.js source code begins with: import { version as VERSION } from '../package.json'; import 'mediacms-vjs-plugin-font-icons/dist/mediacms-vjs-icons.css'; ...

Apply CSS styling to options specifically in Internet Explorer

How can I style options in a select list using CSS? I have successfully styled the options in Mozilla Firefox, but the styles do not apply in Internet Explorer and Chrome. Here is a jsFiddle link for IE <select class="mapField"> <option valu ...

Guide to crafting a custom asynchronous function in a separate file using Express JS

I have a specific function that I want to create called: my_function.js: module.exports = function(req, res, next){ var js_obj; // Do something with the JavaScript object above // Afterwards, I want to append "js_object" to the request object: req.js ...

The content of XMLHttpRequest is accessible via the property response

Typically, when we want to retrieve data using AJAX, we would use code like this: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ elem.innerHTML = xhr.responseText; ...

saving a JSON element in a JavaScript array

Currently, I am utilizing AJAX to fetch data from a database using PHP and then converting it into JSON format. <?php echo json_encode($data); ?> This is the AJAX function being used: ajaxCall("getdata.php", container, function (data) { var co ...

Incorporate a background image property using Jquery

Can anyone help me with adding the css background-image:url("xxxxx") property to my code? jQuery('#'+$trackID+' .sc_thumb').attr('src',$thumb_url); jQuery('#'+$trackID+' .sc_container').css('display& ...

Asynchronously updating a Django model instance in real-time

On my website, there is a button that allows users to view notifications as a drop-down without navigating away from the current page. I am interested in updating the unread field of every notification for a user from True to False when this button is clic ...

Retrieve information and functions from one component in a separate component

I currently have two components: ContainerSidebar.vue <!-- Sidebar --> <div id="b-sidebar"> <div class="change-image"> <img :src="profile.avatar != null ? profile.avatar+'#&apo ...

Solving the issue of overflowing in the animation on scroll library

I've recently started using a fantastic library called animation on scroll (aos) for my web development projects. This library offers stunning and visually appealing animations. However, I encountered an issue where it causes overflow problems in my H ...

Discover the exclusive Error 404 dynamic routes available only in the production version of NEXT13! Don

Hey everyone, I'm encountering an issue with NEXT's dynamic routing (Next 13). My folder structure looks like this: - user/ -- [id]/ --- page.js It works fine in dev mode but not in production. What am I trying to do? I've created a "page ...

What is the best way to flatten an array of objects in NodeJS?

Looking to unravel an array of nested objects containing arrays of objects. The level of nesting varies and is inconsistent throughout the array. Below is a snippet of the provided data var data = [{ id: 1, name: 'Harshal', subjects ...

How can input be fixed in place within a list inside an Ionic framework popover?

I have the following code in a popover template: <ion-popover-view class="customPopup"> <ion-header-bar class="bar bar-header barHeaderCustom"> <h1 class="title">{{ 'AVAILABLE_SOUNDS' | translate }}</h1> </io ...

Is there a way to deactivate the mobile version of Facebook Comments? And, what criteria determine whether a device is considered mobile or not?

I'm now designing Facebook Comments for my personal Wordpress. But I got stuck for the setting on mobile version of it. https://i.sstatic.net/tccLx.png Desktop version of Facebook Comments https://i.sstatic.net/L7Ppy.jpg Mobile version of Facebook Co ...

PHP: Colorize a section of an image and store the data

My goal is to create a webpage featuring grid paper images that users can interact with. They will be able to select individual grids and fill them with color based on the link they choose, which will then be saved. Once all grids are filled, the page wi ...

Browsing through a jQuery JSON object in Chrome reveals a dynamic reshuffling of its order

Jquery + rails 4 Within the json_data instance, there is data with key-value pairs. The key is an integer ID and the value is an object containing data. However, when attempting to iterate over this data using the jQuery $.each function, the results are s ...

Navigating through the nested object values of an Axios request's response can be achieved in React JS by using the proper

I am attempting to extract the category_name from my project_category object within the Axios response of my project. This is a singular record, so I do not need to map through an array, but rather access the entire object stored in my state. Here is an ex ...

What is the best way to increase dates in javascript?

I am working with a datetimepicker that has date and time format. I need to be able to add a specific number of days to the selected datetime. The datetime input will be selected from the datetimepicker input datetime = Friday, October 23rd 2015, 12:00:0 ...