Mohsen Movahed
Mohsen Movahed

Reputation: 496

New line is not working in editable div

This is Html code:

<div id="messageBox" contenteditable="true" class="message"></div>

And this is jquery:

$('#messageBox').keydown(function(e) {
        if (e.ctrlKey && e.keyCode == 13)
        {
            $(this).html($(this).html() + "<br>");
        }
    }).keypress(function(e) {
        if(e.keyCode == 13)
        {
            $('#send').trigger('click');
            return false;
        }
    });

I want to create a new line by pressing Ctrl+Enter but it does not work.The cursor does not move.
JS FIDDLE

Upvotes: 4

Views: 1584

Answers (2)

scniro
scniro

Reputation: 16989

There is a way to get this working for you as I'll provide below. I would suggest pre populating your <div> with a <br /> like

<div id="messageBox" contenteditable="true" class="message">
    <br />
</div>

Although thus looks weird, it gets the browser an "anchor" to place the cursor on to start. You'll notice odd behavior if you remove this and try to "add a new line" for the first time. Also as a comments suggest, you were overlaying your html each time, which could generate a lot of overhead and undesired behavior depending on how involved your project becomes, so for this example I simply append as such $(this).append('<br />')

JSFiddle Link

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != 'undefined'
            && typeof document.createRange != 'undefined') {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != 'undefined') {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

$('#messageBox')
    .keydown(function(e) {
        if (e.ctrlKey && e.keyCode == 13) {            
            $(this).append('<br />');    
            placeCaretAtEnd($('#messageBox').get(0));
        }
    }).keypress(function(e) {
        if(e.keyCode == 13) {
            $('#send').trigger('click');
            return false;
        }
});

Upvotes: 1

Michael
Michael

Reputation: 1

Sample works for me just fine. Make sure your browser supports contenteditable. Below is the list of browsers that do support it.

Chrome  4.0+
Safari  3.1+
Mobile Safari   5.0+
Firefox 3.5+
Opera   9.0+
Opera Mini/Mobile   N/A
Internet Explorer   5.5+
Android 3.0+

Also, in same cases you might need to wrap it in a container that has contenteditable="false".

The cursor is not going to move, since you're only appending the text. Check this on how to move the cursor to the end How can you move the cursor to the last position of a textarea in Javascript?

Upvotes: 0

Related Questions