Reputation: 9787
When the user press enter in a contentEditable div it generates divs. How can I avoid this and create p or/and br ? (Please, only jQuery)
here to play and check: http://jsfiddle.net/r4gaftj2/
jQuery:
$('#input').keypress(function(e) {
if(e.which == 13) { // if press enter
// alert('You pressed enter!'); //it works
// it does not work:
// e.preventDefault();
// $('#input').append("<br>");
// $(this).html('<br><br>');
}
});
HTML:
<div id="input" contenteditable="true"> </div>
Upvotes: 1
Views: 79
Reputation: 2858
A little bit complicated but works.
Native object sometimes don't have toString implementation and returns nil. That's why you have nothing in alert. Instead of alert please use console.info.
$('#input').keypress(function(e) {
if(e.which == 13) {
// Get current cursor position
// This is section object
var s = window.getSelection();
// Get range object, this object gives you
// possibility to add new elements after cursor position.
var range = s.getRangeAt( 0 );
e.preventDefault();
// creating initial br
var last = document.createElement('br');
// Initial br
range.insertNode( last );
// Parent container (editable node)
var container = s.focusNode;
// If cursor is inside text container will be text node, need to pull up.
if ( container.nodeType != HTMLElement.ELEMENT_NODE )
container = container.parentNode;
if ( last == container.children.item( container.children.length-1 ) && last.previousSibling && last.previousSibling.nodeType == HTMLElement.ELEMENT_NODE ) {
// After BR was other element node so it\s safety to add only one BR.
} else if ( !last.previousSibling || last.previousSibling.nodeType == HTMLElement.TEXT_NODE || (last.nextElementSibling && last.nextElementSibling.tagName != 'BR') ) {
// If first node: to see new line need br and something and this can't be text node...
// If next isn't BR need to create second to see new line (see above)
last = document.createElement('br');
range.insertNode( last );
}
// Cleanup cursor
s.removeAllRanges();
// move cursor after last added node
range.setStartAfter( last );
range.setEndAfter( last );
// set new cursor position
s.addRange( range );
}
});
Upvotes: 1