Prevent contenteditable adding <div> on ENTER - Chrome

iConnor picture iConnor · Aug 31, 2013 · Viewed 95.5k times · Source

I have a contenteditable element, and whenever I type some stuff and hit ENTER it creates a new <div> 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 <br>?

Here is demo http://jsfiddle.net/jDvau/

Note: This is not an issue in firefox.

Answer

Ram G Athreya picture Ram G Athreya · Dec 5, 2013

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/>');
        // prevent the default behaviour of return key pressed
        return false;
    }
});

Click here for demo