Tips for ensuring that the placeholder remains visible as the user begins to type the first few characters of the placeholder text

Typically, when an input placeholder is used, the placeholder text disappears as soon as the user starts typing.

I'm considering providing users with a random example within the input field so they can follow along like they would with a placeholder. The issue arises when the user begins typing and the example disappears. Is there a way to keep the placeholder visible even if the user only types part of it?

For example:

Let's say the placeholder text is 'Lorem ipsum dolor sit amet'. If the user types 'Lorem ipsum', I expect them to try and replicate the example, keeping the text visible. However, if they type something different like 'Lorem dolor', indicating they are deviating from the example, I'd like the placeholder text to reappear after pressing 'backspace' until it matches the original placeholder (e.g. deleting 'dolor' to revert back to 'Lorem').

Currently, my workaround involves using an autocomplete dropdown, but I'm keen to explore if this functionality can be achieved using JavaScript (preferably jQuery).

UPDATE

I've made some progress by attempting to clone an element while maintaining the same style as the text input.

Here's a rough implementation:

var textinput = $('#textinput');
var textplaceholder = $('<span>');
var placeholdertext = textinput.attr('placeholder');
textinput.attr('placeholder', '');

textplaceholder.insertAfter(textinput);
textplaceholder.html(placeholdertext);
textplaceholder.copyCSS(textinput);

textinput.keyup(function() {
    var current = $(this).val();
    if(placeholdertext.substr(0, current.length) == current){
        textplaceholder.html(placeholdertext);
    } else {
        textplaceholder.html(current);
    }
});

Check out the fiddle here.

The challenge now lies in positioning the cloned element behind the input text, ensuring uniform alignment across browsers, and replicating mouse interactions like border glow when the text is focused on, etc.

Answer №1

There are numerous methods to achieve a similar effect. Here is one approach:

<div class="container">
    <span class="text-box" contentEditable="true">Lorem i</span><span class="highlight"></span>
</div>
<!-- use some CSS styling for the desired appearance -->
var text = "Lorem ipsum";

$(".container > .text-box").on("input", function(){
    var inputText = $(this).text().replace(/\u00A0/g, " ");
    //dealing with NO-BREAK SPACE requires special attention
    if(text.indexOf(inputText) == 0){
        $(".highlight").text(text.substr(inputText.length, text.length));
    }else{
        $(".highlight").text("");
    }
}).trigger("input");

http://jsfiddle.net/DerekL/7sD2r/

To learn more about the NO-BREAK SPACE, refer to here.

Answer №2

If you want to achieve a certain result, consider implementing this code snippet or following this approach.

Take a look at the code provided below:

fiddle

html

<div id="main">
    <input TYPE="TEXT" id="in1"/>
    <div id="back"> sanmveg</div> 

</div>

css

    #back{
    //background-color:#ccc;
    width:200px;
    height:22px;
    margin-top:-21px;
    margin-left:4px;
    font-family:arial;
    font-size:13px;
}

#main{
    width:200px;
    height:20px;
}

#in1{
    //background-color:#EEE;
    opacity:.7;
    font-family:arial;
}

By utilizing only HTML and CSS, I was able to fulfill your requirement.

explanation

The implementation involved using HTML and CSS. The transparency of the input field is minimal, positioned over a div box with text inside. The div element is strategically placed so that the text aligns with the cursor position when typing in the input field.

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

The JSON information is not appearing as expected

Utilizing a jQuery function, I am attempting to access a JSON file: $.ajax({ type: 'GET', url: '/data/coffee.json', dataType:'json', success: function(data) { let widget = displayData(data); $(" ...

Incorporating PHP Variables into JQuery's Ajax Data

It's pretty obvious that I'm still getting the hang of jQuery. If you have any better suggestions for achieving what I'm trying to do, please feel free to share :) Here's the issue I'm facing. The script runs smoothly when you repl ...

Ways to manage the duration of the message pop-up window's display

Whenever the disk format is in progress, I utilize this.$toast() to notify the user. However, the message only displays for 1 second. I want the message to persist until the formatting is completed. How can I achieve this? ...

Sending arrays as parameters to a TypeScript constructor

Recently, I delved into creating an Idle Game in TypeScript (similar to cookie clicker, but not quite as refined yet!). My knowledge of TypeScript and JavaScript is still at a beginner level. The challenge arose when I decided to switch the "cost" attribu ...

The autofocus feature does not function properly while utilizing the onMouseDown event

There are two very similar components that control the focus for the input when it is displayed: Check out this example here Or explore this one In the second scenario, I opted for using the onMouseDown event instead of onClick for the button that trigg ...

I must condense an array

How can I flatten an array of objects: var mylist = [{ THEMEID: 1, TITLE: "myTheme1", PARENTID: 0, children: [{ ITEMID: 1, NAME: "myItem1", THEMEID: 1, PARENTID: 1, TITLE: "myItem1" }, ...

Steps to modify the background color of an IconButton upon clicking in Material UI

After clicking on the IconButton, the background color changes to an oval shape. I now need to modify the background color when it is clicked. CSS The CSS code for the IconButton changes the background color upon hover. I require a similar effect for the ...

How to Enhance jqGrid with a Custom Button to Redirect to a Different URL

I want to add a custom button next to the refresh button on the navigation panel of my jQgrid. When this custom button is clicked, I need it to open a specific URL in a new browser window. Below is the code snippet that I currently have... <!DOCTYPE h ...

Impact when returning a React.FC Component

Using React, I have encountered a challenge with my site: I have a function that generates a Card component displaying information about my store's products (#1). To display this on the screen, I map through the array returned by the backend and pass ...

What is the best way to resize several divs while ensuring they remain within a specific container?

In the process of creating a grid UI, I want users to be able to click on cells and scale them. Intended Outcome: Cells should be prevented from scaling out of the container and being cropped. Cells can overlap with one another when scaled. Only one cel ...

Receive text notifications from web browsers

Is there a way to extract notification text from browser push notifications using JavaScript? I am looking to implement a timeout function to check the content of the notification. Alternatively, is it possible to subscribe to an event triggered by the n ...

DOMPDF rearranges the order of HTML elements

I am currently using Laravel and working with an HTML view that includes integrated CSS. My goal is to convert this view into a PDF format. When I open the view directly (whether through my documents or a link in my application), everything displays correc ...

Can VueJS lifecycle hooks be outsourced?

Is it possible to organize lifecycle hooks (like created / mounted) in a separate file for better simplicity and cleanliness? MyGreatView.vue import created from 'created.js' export default { created, // created() { console.log('vue Cre ...

Why is my element still occupying space even though it has been hidden with a display of none?

Currently, I'm working on a dropdown navigation menu where one of the list items causes space issues when the display property is set to none. Specifically, the 'Book A Table' item isn't meant to be visible in the center div when the sc ...

Encountering an Invalid Argument Script Error while using Internet Explorer 11 on Windows 10

I encountered an issue with an Invalid Argument script error in Windows 10 using IE 11. However, the code runs smoothly on Windows 7. Please refer to the attached screenshot and see if anyone can offer assistance. Here is the code snippet: var tbl = docum ...

Received a collection of null values within the Semantic UI search dropdown

In my rails + angular application, I am utilizing semantic ui. There is a search dropdown that displays undefined values when typing the letter s, but works fine for other single letters. Strangely, no server request is made when typing the letter s, and I ...

Steps to swap out an array string with a user-entered string

Greetings, I am a newcomer to StackOverflow and seeking assistance with a code snippet that replaces every underscore in a given string. public class MainActivity extends AppCompatActivity { private String result=""; private String textresult = "The red f ...

Guide to accessing a method from a separate file with the help of an event bus

I'm working on CreateEntryStepper.vue where I have a button that needs to call a function in CreateEntryStepperImageUpload.vue when pressed. I understand that event busses need to be used, but I am unsure about what exactly needs to be passed and how ...

Error: The JavaScript engine Hermes is throwing a TypeError because it is unable to access the property 'navigate' which is undefined

Trying to set up react navigation has been a challenge, especially when attempting to move navigation items into their individual components. Below is a Stack Navigator within APP.js: import React from 'react'; import { StyleSheet, Text, View } ...

The Django framework encountered an error when trying to divide two dictionaries: unsupported operand type(s) for /: 'dict' and 'dict'

I'm unsure of the best way to display the "net margin" result in HTML, which is calculated as net profit divided by sales. Rather than inserting this division formula directly into the HTML code due to other complex calculations involved, how can I sh ...