Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placeholder in contenteditable - focus event issue

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.

like image 693
David Hellsing Avatar asked Feb 01 '12 09:02

David Hellsing


People also ask

How do you focus on Contenteditable?

Changing your tabIndex to >= 0 will let you focus on the elements. If you need to do it dynamically, you can just add a tabindex >= 0 to your element in the event listener.

What is false about Contenteditable attribute?

contenteditable="false" Indicates that the element is not editable. contenteditable="inherit" Indicates that the element is editable if its immediate parent element is editable.

How do I stop Enter key in Contenteditable?

To prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript, we can listen for the keydown event on the contenteditable element and prevent the default behavior when Enter is pressed. to add a contenteditable div. document. addEventListener("keydown", (event) => { if (event.


1 Answers

Here is a CSS only solution augmenting some of the other answers:-

<div contentEditable=true data-ph="My Placeholder String"></div> <style>     [contentEditable=true]:empty:not(:focus)::before{         content:attr(data-ph)     } </style> 

EDIT: Here is my snippet on codepen -> http://codepen.io/mrmoje/pen/lkLez

EDIT2: Be advised, this method doesn't work 100% for multi-line applications due to residual <br> elements being present in the div after performing a select-all-cut or select-all-delete on all lines. Credits:- @vsync
Backspace seems to work fine (at least on webkit/blink)

like image 152
mrmoje Avatar answered Sep 17 '22 14:09

mrmoje