Reputation: 1088
https://jsfiddle.net/cp1ntk45/
I write a function to replace original html placeholder, then I can style the placeholder text.
it works fine with input and textarea element,
problem if the target is
contentEditable div, after click once not focus in, not be able to type, need to click second times to focusin ...
How to make only click one time and focus in
var placeholder = function(el) {
el.on('focusin', function() {
var val = $(this).text();
var placeholder = $(this).attr('data-placeholder');
if (val == placeholder) {
if ($(this).attr('data-empty') != 'false') {
$(this).text('');
}
}
});
el.on('focusout', function() {
var val = $(this).text();
var placeholder = $(this).attr('data-placeholder');
if (val == '') {
$(this).text(placeholder);
$(this).attr('data-empty', 'true');
} else {
$(this).attr('data-empty', 'false');
}
});
};
placeholder($('.textarea'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="textarea" contentEditable="true" data-placeholder="placeholder">placeholder</div>
Upvotes: 9
Views: 7160
Reputation: 206121
You can use CSS :empty
and :before
on your contenteditable
element.
Using the content: attr(data-placeholder);
you can then stamp any text you want.
[contenteditable] {padding:12px; background:#eee; }
[data-placeholder]:empty:before{
content: attr(data-placeholder);
color: #888;
font-style: italic;
}
<div contenteditable data-placeholder="I'm a placeholder"></div>
Upvotes: 19
Reputation: 1088
solve this by change the attribute contentEditable
after click and focusout event, like below
el.on('click', function() {
$(this).attr('contentEditable', 'true');
$(this).focus();
});
el.on('focusout', function() {
$(this).attr('contentEditable', 'false');
});
https://stackoverflow.com/a/15993398/5593189
Upvotes: 0