HTML5 contenteditable Backspace Bug Fix

When editing text in HTML5’s contenteditable attribute you probably need to have all of your content wrapped with <p> or <div> tags like so.

<p>My text</p>
<p>Another line of text</p>

The problem is if you do the following it will screw up your block formatting and dump in empty lines of text. Which is nasty formatting you don’t want and the cursor placement will start wacking out in your contenteditable area.

  1. Select all text
  2. Press delete a few times
  3. Type some text, hit enter, type some more text
  4. Observe that your formatting is now completely messed up like so
My text
<div>Another line of text</div>

Thankfully the fix is easy, you just need to hijack the keypress event to check if an empty line is present with a little JavaScript.

var $editor = $('#editorId');
$editor.keypress(function (e) {
  var html = $editor.html();
  if (html === '' || html === '<br>') {
    document.execCommand('formatBlock', false, 'p');
  }
});

One thought on “HTML5 contenteditable Backspace Bug Fix”

Leave a Reply

Your email address will not be published. Required fields are marked *