Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a "placeholder" for DIV that act like textfield?

Div don't have a placeholder attribute

<div id="editable" contentEditable="true"></div> 

I want <Please your enter your Name> to show in DIV when the User backspace the whole text in the DIV, or no text on inside, How can I do it?

like image 458
user2399158 Avatar asked Jun 05 '13 13:06

user2399158


People also ask

Can I put a placeholder in a div?

Although you can make an editable div by using the contenteditable attribute, it will not support the placeholder attribute.

What is placeholder in textfield?

The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format). The short hint is displayed in the input field before the user enters a value.

How do you add a placeholder to a text box in HTML?

If you want to set a hint for text area or input field, then use the HTML placeholder attribute. The hint is the expected value, which gets displayed before the user enters a value, for example, name, details, etc.


1 Answers

Here is a pure CSS only solution:-

<div contentEditable=true data-ph="My Placeholder String"></div> <style>     [contentEditable=true]:empty:not(:focus):before{         content:attr(data-ph)     } </style> 

Here, we basically select all contentEditable <divs> that are empty & blurred. We then create a pseudo element before the CSS selection (the editable div) and fix our placeholder text (specified the data-ph attribute) as its content.

If you are targeting old school CSS2 browsers, change all occurrences of data-ph to title
Correction.......the :empty selector is not supported in IE version 8 and earlier.

like image 114
mrmoje Avatar answered Sep 17 '22 21:09

mrmoje