I’ve been looking for work at Google for more than a week, I’m trying to implement various solutions, but without success, and this distracted me from me.
So, you have a contenteditable div with multiple paragraphs (or other children of the same type). Obviously, this is the model you want to keep. If the user selects two or more paragraphs and types above him, he deletes the paragraphs and sets the caret focus inside the parent div:
body { font-family: georgia; } .editable { color: red; } .editable p { color: #333; } .editable span { color: limegreen !important; }
<div class="editable" contenteditable><p>paragraph one</p><p>paragraph two</p></div> <hr> <p>How to reproduce the bug:</p> <ul> <li>Focus the contenteditable above by placing the cursor somewhere in one of the two paragraphs.</li> <li>press ctrl-a (in windows or linux) or cmd-a (in osx) to select-all</li> <li>type some text</li> <li>red text means that the text went directly inside the contenteditable div, black text means it went inside a paragraph</li> </ul> <p>The correct behaviour should be that that select-all and delete (or "type-over") in a contenteditable with only block tags should leave the cursor inside the first block tag.</p> <p>Webkit gets this right, Firefox gets it wrong.</p>
I tried to do something like this in jQuery:
$(document).on('blur keyup','div[contenteditable="true"]',function(event){ var sel = window.getSelection(); var activeElement = sel.anchorNode.parentNode; var tagName = activeElement.tagName.toLowerCase(); if (!(tagName == "p" || tagName == "span")) { console.log('not on editable area'); event.preventDefault();
So, after the blur or keyup event is contenteditable, find where the carriage position is and if it stops the event or something else outside the accepted editable areas?
I tried to change the range of choice and a bunch of other things, but maybe I just don't see it. I’m sure many people had the same problem, but the only answers I found on Google, or here is “editable content”, “why don’t you just use the open source editor” and such things.
strange behavior of Firefox: pasting BR tags into the interrupt string I also tried to remove the strange behavior of Firefox by using the function to remove all the <BR> tags that automatically insert firefox. Like this:
function removeBr(txteditor) { var brs = txteditor.getElementsByTagName("br"); for (var i = 0; i < brs.length; i++) { brs[i].parentNode.removeChild(brs[i]); } }
So, I attached this to the keydown event, and it does exactly what it expected, however it causes more weird behavior (for example, preventing spaces from being added to the selected paragraph).
Please vote on the question so that we can raise awareness.
I am sure that many other people have faced the same problem, I think it would be nice to know if there is a workaround or any “right” way to do this. I think it really needs to be discussed ...