Placeholder for contenteditable div
I have the following: FIDDLE
The placeholder works fine and dandy until you type something, ctrl + A, and delete. If you do that, the placeholder disappears and never shows up again.
What's wrong? How can I have a placeholder for a contenteditable div?
HTML:
<div class="test" placeholder="Type something..." contenteditable="true"></div>
CSS:
.test {
width: 500px;
height: 70px;
background: #f5f5f5;
border: 1px solid #ddd;
padding: 5px;
}
.test[placeholder]:empty:before {
content: attr(placeholder);
color: #555;
}
Thanks.
While searching for the same problem I worked out a simple mixed css-JavaScript solution I'd like to share:
CSS:
[placeholder]:empty::before {
content: attr(placeholder);
color: #555;
}
[placeholder]:empty:focus::before {
content: "";
}
JavaScript:
jQuery(function($){
$("[contenteditable]").focusout(function(){
var element = $(this);
if (!element.text().trim().length) {
element.empty();
}
});
});
Updated fiddle
from Placeholder in contenteditable - focus event issue
[contenteditable=true]:empty:not(:focus):before{
content:attr(data-ph);
color:grey;
font-style:italic;
}
I've created a live demo: "Placeholder for content-editable divs", by HTML & CSS.
Also, Codepen: https://codepen.io/fritx/pen/NZpbqW
Ref: https://github.com/fritx/vue-at/issues/39#issuecomment-504412421
.editor {
border: solid 1px gray;
width: 300px;
height: 100px;
padding: 6px;
overflow: scroll;
}
[contenteditable][placeholder]:empty:before {
content: attr(placeholder);
position: absolute;
color: gray;
background-color: transparent;
}
<textarea class="editor"
placeholder="Textarea placeholder..."
></textarea>
<br/>
<br/>
<div class="editor"
contenteditable
placeholder="Div placeholder..."
oninput="if(this.innerHTML.trim()==='<br>')this.innerHTML=''"
></div>
I got this solution from: https://codepen.io/flesler/pen/AEIFc
Basically put this css code:
[contenteditable=true]:empty:before{
content: attr(placeholder);
pointer-events: none;
display: block; /* For Firefox */
}
And have the placeholder attribute in your contenteditable div.