I am making a simple editor for my project where I need to use an editable div using the contenteditable
property. I need two functions:
- Auto insert hr after two inputs
- Create a paragraph instead of
<br>
to enter and focus on it.
So I wrote this (with some inspiration), this is part of the code that answers:
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 does not create a new <p>
element, I think it just wraps the current text in p
, which is impossible because it is already in p
. That way, the cursor just stays in firefox and no new paragraph is created.
Do you have an idea how to fix this? Thanks.
source share