Backspace on start/empty removes wrapper tags
alexslade opened this issue · comments
You can see this on the demo page. Select everything, delete and delete again. You can now type and your text won't be formatted properly. Start a new line and you're back inside a paragraph tag.
<article class="content" contenteditable="true">
Look ma, no tags!
<div><p>
From tags to riches.
</p></div>
</article>
I came across the same problem and in my app I wrote this noob jquery monkeypatch to get round it:
$('#youreditor').keyup(function(){
if (!$(this).html()) {
$(this).append('<p> </p>');
var sel = window.getSelection();
var range = sel.getRangeAt(0);
sel.removeAllRanges();
sel.addRange(range);
}
});
It's probably not very performant as it runs on every keyup but it's all I could come up with. It needed keyup and not keydown in order for it to work with backspace and it needed a character of some sort in the paragraph tag or it didn't want to put the caret in it.
In my app I use the rangy plugin so instead of:
window.getSelection();
I use:
rangy.getSelection();
for better browser compatibility when using range.
@AidanZealley Yep definitely the issue here, the cross-browser compatibility for ranges and selections is not really great - this is something that we'll have to put up with for now.