Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Similar to your attempt, we modify the contenteditable when the user presses Enter: <a href="http://jsfiddle.net/jefferyto/dqCWd/">Demo</a></p> <pre><code>if (window.getSelection) { // w3c $('div').keypress(function (e) { var sel, node, children, br, range; if (e.which == 13) { sel = window.getSelection(); node = $(sel.anchorNode); children = $(sel.anchorNode.childNodes); // if nothing is selected and the caret is in an empty &lt;li&gt; // (the browser seems to insert a &lt;br&gt; before we get called) if (sel.isCollapsed &amp;&amp; node.is('li') &amp;&amp; (!children.length || (children.length == 1 &amp;&amp; children.first().is('br')))) { e.preventDefault(); // if the empty &lt;li&gt; is in the middle of the list, // move the following &lt;li&gt;'s to a new list if (!node.is(':last-child')) { node.parent().clone(false) .empty() .insertAfter(node.parent()) .append(node.nextAll()); } // insert &lt;br&gt; after list br = $('&lt;br&gt;').insertAfter(node.parent()); // move caret to after &lt;br&gt; range = document.createRange(); range.setStartAfter(br.get(0)); range.setEndAfter(br.get(0)); sel.removeAllRanges(); sel.addRange(range); // remove &lt;li&gt; node.remove(); } } }); } else if (document.selection) { // internet explorer $('div').keypress(function (e) { var range, node, children; if (e.which == 13) { range = document.selection.createRange(); node = $(range.parentElement()); children = $(range.parentElement().childNodes); // if nothing is selected and the caret is in an empty &lt;li&gt; // (the browser seems to insert a &lt;br&gt; before we get called) if (!range.htmlText.length &amp;&amp; node.is('li') &amp;&amp; (!children.length || (children.length == 1 &amp;&amp; children.first().is('br')))) { e.preventDefault(); // if the empty &lt;li&gt; is in the middle of the list, // move the following &lt;li&gt;'s to a new list if (!node.is(':last-child')) { node.parent().clone(false) .empty() .insertAfter(node.parent()) .append(node.nextAll()); } // insert &lt;br&gt; after list br = $('&lt;br&gt;').insertAfter(node.parent()); // move caret to after &lt;br&gt; range = document.body.createTextRange(); range.moveToElementText(br.get(0)); range.collapse(false); range.select(); // remove &lt;li&gt; node.remove(); } } }); } </code></pre> <p>Note that this doesn't handle the case where the user has selected something before pressing Enter. If you want to handle this case, you'll need to figure out if the user has selected the entire contents of the <code>&lt;li&gt;</code> (this doesn't seem like a trivial task), and if so, delete the contents and treat it the same as if the user pressed Enter in an empty <code>&lt;li&gt;</code>.</p>
 

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