HTML5 contenteditable new line jumps twice

663 Views Asked by At

In the example bellow there is some strange behaviour regarding new lines. For an example in Chrome when you press enter twice the row cursor jumps 3 lines down instead of 2. In Firefox it jumps like this all the time.

jQuery("#message").on("keydown", function (event) {
  if (event.keyCode === 13) {
    document.execCommand('insertHTML', false, '\n\n');
    return false;
  }
});

jQuery("#message").on("keyup", function () {
  jQuery("#outcome").html(jQuery(this).html());
});
#message, 
#outcome {
  width: 100%;
  height: 100px;
  border: 1px solid black;
  white-space: pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="message" contenteditable></div>

<div id="outcome"></div>

EDIT: This code seems to work perfectly in all browsers but firefox.

jQuery("#message").on('keydown', function (event) {
  var elem = $(this);
  if (event.keyCode === 13 || event.keyCode === 10) {
    event.preventDefault();

    if (JSON.stringify(elem[0].innerHTML).slice(-3).slice(0, 2) === '\\n' || !elem[0].innerHTML.length) {
      return false;
    }

    document.execCommand('insertHTML', false, '\n\n');
    return false;
  }
});

jQuery("#message").on("keyup", function () {
  jQuery("#outcome").html(jQuery(this).html());
});
#message, 
#outcome {
  width: 100%;
  height: 100px;
  border: 1px solid black;
  white-space: pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="message" contenteditable></div>

<div id="outcome"></div>

1

There are 1 best solutions below

1
On

It probably jumps 3 lines because the enter key injects a new line and after that you inject 2 more new lines.

Try doing this:

jQuery("#message").on("keydown", function (event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        document.execCommand('insertHTML', false, '\n\n');
        return false;
    }
});