Search code examples
javascriptangularjswysiwygcontenteditableexeccommand

Implement new Line Change on pressing "Enter" key


I am using contenteditable where I because of some business scenarios, I need to track the new line breaks <br>. To handle that, I did below steps:

  1. On keydown event, I stopped "enter" key event (keyCode = 13)
  2. On keyup event of "Enter", I fire execCommand as $window.document.execCommand('insertHTML',true,'<br class="new">');

It works like a charm unless I am at the line end.

Problem

  • When the cursor is at the line end, first enter keypress inserts <br class="new"> but line change of cursor do not happen although the html is inserted.
  • When I press the enter again, nothing happens. No innerHTML is inserted.

Here is the plunkr. Please check console to see the html

It works perfect if there is any character before cursor

I hope I have explained my problem clearly. Any suggestions please


Solution

  • Although it seems like a workaround, but you can use &nbsp;

    $window.document.execCommand('insertHTML',true,'<br class="new">&nbsp;');
    

    It'll serve your purpose with a whitespace , which I think can be ignored.