New line not working in editable div
This is the 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
There is a way to make this work for you, as I will discuss below. I would suggest pre-populating your <div> <br />like
<div id="messageBox" contenteditable="true" class="message">
<br />
</div>
, "", . , " " . , , html, , , $(this).append('<br />')
JSFiddle
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;
}
});
. , . , .
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+
, contenteditable = "false".
, . , Javascript?