ryanpika
ryanpika

Reputation: 151

Javascript: how to trigger a backspace keypress when pressing enter key in conteditable div?

Due to some complicated reason, When user press enter key in contenteditable div, I have to hard code to imitate the normal behavior of changing lines, my attempt was that when enter key is pressed, first, two br tags then created (works fine)and then second, delete last br by imitating user's pressing on backspace (works not fine).

My attempt is below, which fails to imitate user's backspace keypress at the caret position.

html:

<div id="hithere" style="border:1px solid black" contenteditable="true" autocomplete="off" spellcheck="false"></div>

Javascript:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 

<script>
$('div[contenteditable]').keydown(function(e) {

    if (e.keyCode === 13) {

                 document.execCommand('insertHTML', false, ' <br><br>');
                     $(function() {
                     var bre = $.Event('keypress');
                        bre.keyCode= 8; // enter
                    document.trigger(bre);
                    });
    }

    //   // prevent the default behaviour of return key pressed
    return false;
  });
</script>

Upvotes: 0

Views: 2414

Answers (1)

Ben Philipp
Ben Philipp

Reputation: 1877

I saw the problem which you probably ran into but didn't write about: The <br /> is inserted, but when the user continues typing, the text gets inserted above the break.

You can insert the break as Text instead, using the two components \r and \n (Carriage Return and New Line)

document.execCommand('insertText', false, '\r\n');

See here: https://jsfiddle.net/svArtist/6o5ao1bm/1/

Upvotes: 1

Related Questions