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 />')
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;
}
});
`. It gets inserted, but the browser doesn't display it. You can verify this by changing your `"
"` to `"
foo"`. – elixenide Feb 01 '15 at 19:13