Prevent contenteditable adding
on ENTER – Chrome

Loading...

Prevent contenteditable adding

on ENTER – Chrome

I have a contenteditable element, and whenever I type some stuff and hit ENTER it creates a new

and places the new line text in there. I don’t like this one little bit.
Is it possible to prevent this from happening or at least just replace it with a
?
Here is demo http://jsfiddle.net/jDvau/
Note: This is not an issue in firefox.

Solutions/Answers:

Solution 1:

Try this

$('div[contenteditable]').keydown(function(e) {
    // trap the return key being pressed
    if (e.keyCode === 13) {
      // insert 2 br tags (if only one br tag is inserted the cursor won't go to the next line)
      document.execCommand('insertHTML', false, '<br><br>');
      // prevent the default behaviour of return key pressed
      return false;
    }
  });

Demo Here

Solution 2:

You can do this with just a CSS change:

div{
    background: skyblue;
    padding:10px;
    display: inline-block;
}

pre{
    white-space: pre-wrap;
    background: #EEE;
}

http://jsfiddle.net/ayiem999/HW43Q/

Solution 3:

Add style display:inline-block; to contenteditable, it will not generate div, p and span automatically in Chrome.

Solution 4:

Try this:

$('div[contenteditable="true"]').keypress(function(event) {

    if (event.which != 13)
        return true;

    var docFragment = document.createDocumentFragment();

    //add a new line
    var newEle = document.createTextNode('\n');
    docFragment.appendChild(newEle);

    //add the br, or p, or something else
    newEle = document.createElement('br');
    docFragment.appendChild(newEle);

    //make the br replace selection
    var range = window.getSelection().getRangeAt(0);
    range.deleteContents();
    range.insertNode(docFragment);

    //create a new range
    range = document.createRange();
    range.setStartAfter(newEle);
    range.collapse(true);

    //make the cursor there
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);

    return false;
});

http://jsfiddle.net/rooseve/jDvau/3/

Solution 5:

document.execCommand('defaultParagraphSeparator', false, 'p');

It overrides the default behavior to have paragraph instead.

On chrome the default behavior on enter is:

<div>
    <br>
</div>

With that command it is gonna be

<p>
    <br>
</p>

Now that it’s more linear across it’s easy to have only <br> would you need to.

Solution 6:

Use shift+enter instead of enter to just put a single <br> tag in or wrap your text in <p> tags.

Loading...