Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  102] [ 3]  / answers: 1 / hits: 52531  / 10 Years ago, sun, october 12, 2014, 12:00:00

I have an input like this:



<input value=My text placeholder=Placeholder>


When I type something in the input the placeholder text will disappear, that's quite obvious.



Now, what I want to do is that I want the placeholder text to stay when the user types so you can see the placeholder text as a background text behind the original text:



placeholder



EDIT: I also want to be able to change the background-text using JavaScript.


More From » html

 Answers
32

Hard to think of a good usecase for such a behaviour, as it is blocking some of the users input.



An easy way would be to use input::after but this is not supported by any browser right now (thanks @JukkaK.Korpela).



But you can use a wrapper element and a data attribute, as follows:



<div class=placeholder data-placeholder=my placeholder>
<input value=My text />
</div>


With this css:



.placeholder
{
position: relative;
}

.placeholder::after
{
position: absolute;
left: 5px;
top: 3px;
content: attr(data-placeholder);
pointer-events: none;
opacity: 0.6;
}


Resulting in: enter



Click here for jsFiddle demo.






Since you will have to do a lot of tweaking to make this look good, you may also consider using the wrapping <div> element as a input look alike:



<div class=editable data-placeholder=my placeholder>
<input type=text value=my Text />
</div>


CSS:



.editable
{
position: relative;
border: 1px solid gray;
padding: 3px;
background-color: white;
box-shadow: rgba(0,0,0,0.4) 2px 2px 2px inset;
}

.editable > input
{
position: relative;
z-index: 1;
border: none;
background-color: transparent;
box-shadow: none;
width: 100%;
}

.editable::after
{
position: absolute;
left: 4px;
top: 5px;
content: attr(data-placeholder);
pointer-events: none;
opacity: 0.5;
z-index: 1;
}


Click here for the Demo 3. (with mocked <input />)



Click here for the Demo 2. (with contenteditable)


[#69156] Thursday, October 9, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jameson

Total Points: 534
Total Questions: 103
Total Answers: 102

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
jameson questions
;