9

I tried the following code on Chrome:

document.execCommand("insertBrOnReturn", false, true);

http://jsfiddle.net/uVcd5/

Wether I set the last parameter to true or false, the behaviour doesn't change: on return, new <div> elements will be added.

Must have missed something... any ideas?

Matthew
  • 9,868
  • 7
  • 48
  • 64

3 Answers3

13

insertBrOnReturn is a Mozilla specific command, Chrome doesn't support it. You can test that with:

 document.queryCommandSupported('insertBrOnReturn')

jsFiddle here, it alert true in Firefox, but false in Chrome.

If you want to insert <br> only, try:

document.execCommand('insertHTML', false, '<br><br>');

Also, check this: Prevent contenteditable adding <div> on ENTER - Chrome

vsync
  • 87,559
  • 45
  • 247
  • 317
Andrew
  • 5,128
  • 1
  • 14
  • 21
  • I wonder why Chrome doesn't insert new P elements by default on return instead of DIV. Would you perhaps know the reason for that? – Matthew Dec 16 '13 at 11:04
  • 1
    Actually, you can make P the paragraph separator by this: document.execCommand('defaultParagraphSeparator', false, 'p'); Also it only works for DIV and P. – Andrew Dec 16 '13 at 11:27
4
document.execCommand("insertLineBreak");

According to: https://www.w3schools.com/jsref/met_document_execcommand.asp

You can check the specs command at: https://w3c.github.io/editing/docs/execCommand/#dfn-the-insertlinebreak-command

Reuel Ribeiro
  • 1,129
  • 11
  • 21
  • This was a much appropriate solution for my case than `insertHTML` + `
    `.
    – Reuel Ribeiro Aug 21 '20 at 14:33
  • of all the answers, this works the best without having to do any hacks. the only thing odd about it is that it keeps an unused `
    ` at the end but it doesnt seem visible on the page so it isn't really a problem.
    – fanfare Apr 28 '21 at 19:35
3

I came across this answer but didn't like how in Chrome if your cursor is at the beginning of a paragraph it adds two breaks. Changing the second <br> to \u200C makes Chrome work perfectly, not so much for Safari.

document.execCommand("insertHTML", false, "<br>\u200C");

What is \u200c? Not sure. Found it referenced here.

Dealing with line Breaks on contentEditable DIV

Community
  • 1
  • 1
  • 2
    U+200C is a zero-width non-joiner, much like the U+200B zero-width space. Note that should the user navigate using the arrow keys, it will have a visible effect, the user will need to press twice to navigate to either side of it. – NeilC Nov 02 '16 at 09:40
  • When you want to go back by hitting the `Backspace` key, you will need to hit it twice deleting the new `‌` character and then the `
    `
    –  Apr 15 '20 at 19:34