Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create a paragraph on enter in a contenteditable div?
    primarykey
    data
    text
    <p>I'm making a simple editor for a project of mine, where I need to use an editable div using <code>contenteditable</code> property. I need two features: </p> <ul> <li>Auto insert hr after two enters</li> <li>Create a paragraph instead of <code>&lt;br&gt;</code> on enter and focus on it.</li> </ul> <p>So I wrote this (with some inspiration), this is part of the code that is responsible: </p> <pre><code>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()) === "" &amp;&amp; !$lastElm.prev().is('hr') ){ document.execCommand('insertParagraph', false); $lastElm.replaceWith($('&lt;hr&gt;', {contenteditable: false})); } // Or just add an paragraph else{ document.execCommand('insertParagraph', false, true); } e.preventDefault(); } } } </code></pre> <p>This works fine in Chrome, but in Firefox, it doesnt create a new <code>&lt;p&gt;</code> element, I think it just wraps the current text in a <code>p</code> which isn't possible because it's already in a <code>p</code>. So the cursor just stays there in firefox and new paragraph isn't created.</p> <p>Do you have an idea how to fix this?<br> Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload