Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 832
Bagwell Avatar asked Dec 22 '13 04:12

Bagwell


People also ask

How to set placeholder for a contentEditable element?

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 ...

How to add a placeholder to an empty element using plain CSS?

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.

Can I make a div with a placeholder in HTML5?

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!

How to add ID and data-placeholder attributes to an element?

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.


2 Answers

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

like image 65
Eternal1 Avatar answered Oct 20 '22 21:10

Eternal1


from Placeholder in contenteditable - focus event issue

[contenteditable=true]:empty:not(:focus):before{
  content:attr(data-ph);
  color:grey;
  font-style:italic;
}
like image 35
nicolas Avatar answered Oct 20 '22 21:10

nicolas