Placeholder for contenteditable div Ask Question

Placeholder for contenteditable div Ask Question

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; 
}


ベストアンサー1

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

おすすめ記事