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>
.test {
width: 500px;
height: 70px;
background: #f5f5f5;
border: 1px solid #ddd;
padding: 5px;
}
.test[placeholder]:empty:before {
content: attr(placeholder);
color: #555;
}
Placeholder for a contenteditable element 1 Use the :empty selector#N#We use a custom attribute, data-placeholder, to set the placeholder:#N#<div class="editable"... 2 Handle the events More ...
This can also be achieved without the use of the contentEditable attribute, using plain CSS. Using the :empty pseudo-class along with the ::before pseudo-element you can add a placeholder to an empty element. The following example provides a fallback placeholder for div elements that do not have a data-placeholder attribute defined.
But when we're building an input element with contenteditable, then that's a different story. Placeholders are supported only by html5 elements explicitly created for text input such as input or textarea, so to make a DIV with a placeholder, we have to start writing some code!
First, we add the id and data-placeholder attributes to the element as following: When users focus on the element, we will reset its content if it's the same as the placeholder. Also, when the element loses its focus, its content will be set back to the placeholder if users don't enter anything.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With