I have been trying to ask this before, without any luck of explaining/proving a working example where the bug happens. So here is another try:
I’m trying to replicate a placeholder effect on a contenteditable DIV. The core concept is simple:
<div contenteditable><em>Edit me</em></div>
<script>
$('div').focus(function() {
$(this).empty();
});
</script>
This can sometomes work, but if the placeholder contains HTML, or if there some other processing being made, the editable DIV’s text caret is being removed, and the user must re-click the editable DIV to be able to start typing (even if it’s still in focus):
Example: http://jsfiddle.net/hHLXr/6/
I can’t use a focus trigger in the handler, since it will create an event loop. So I need a way to re-set the caret cursor in the editable DIV, or in some other way re-focus.
All you need is this little solution
Demo: http://codepen.io/flesler/pen/AEIFc
You may need to manually update the selection. In IE, the focus event is too late, so I would suggest using the
activate
event instead. Here's some code that does the job in all major browsers, including IE <= 8 (which a CSS-only alternative will not):Live demo: http://jsfiddle.net/hHLXr/12/
Code:
I've just published a plugin for this.
It uses a combination of CSS3 and JavaScript to show the placeholder without adding to the content of the
div
:HTML:
CSS:
JS:
And that's it.
Here's my way:
It uses a combination of jQuery and CSS3. Works exactly like the html5 placeholder attribute!.
HTML:
CSS3:
jQuery:
DEMO: http://jsfiddle.net/Tomer123/D78X7/