I'm making a simple editor for a project of mine, where I need to use an editable div using contenteditable
property. I need two features:
- Auto insert hr after two enters
- Create a paragraph instead of
<br>
on enter and focus on it.
So I wrote this (with some inspiration), this is part of the code that is responsible:
var intercept = {
keydown: function(e)
{
if( e.which == 13 ){
intercept.enterKey.call(null, e);
}
},
enterKey: function(e)
{
var $lastElm;
// Find the previous elm
if (document.selection) { // IE
$lastElm = $(document.selection.createRange().parentElement());
} else { // everyone else
$lastElm = $(window.getSelection().anchorNode);
}
// Handle enter key
if( !e.shiftKey )
{
// Check if two or more paragraphs
// are empty, so we can add an hr
if(
$.trim($lastElm.text()) === "" &&
!$lastElm.prev().is('hr')
){
document.execCommand('insertParagraph', false);
$lastElm.replaceWith($('<hr>', {contenteditable: false}));
}
// Or just add an paragraph
else{
document.execCommand('insertParagraph', false, true);
}
e.preventDefault();
}
}
}
This works fine in Chrome, but in Firefox, it doesnt create a new <p>
element, I think it just wraps the current text in a p
which isn't possible because it's already in a p
. So the cursor just stays there in firefox and new paragraph isn't created.
Do you have an idea how to fix this?
Thanks.