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

user2399158 picture user2399158 · Jun 5, 2013 · Viewed 27.5k times · Source

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?

Answer

mrmoje picture mrmoje · Aug 22, 2013

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.