Contenteditable / jQuery / Javascript - Select text from cursor / caret to end of paragraph -
i'm trying make new paragraph when enter key pressed. can , works well. cursor middle of paragraph - when enter pressed i'm trying select range cursor position end of paragraph. remove existing paragraph , add new paragraph below.
i'm trying modify code found in answer here: contenteditable - extract text caret end of element
$(document).on('keydown', 'p[contenteditable="true"]', function(e) { if(e.which == 13) { //new paragraph on enter/return e.preventdefault(); var sel = window.getselection(); if (sel.rangecount) { var selrange = sel.getrangeat(0); var blockel = selrange.endcontainer.parentnode; var range = selrange.clonerange(); range.selectnodecontents(blockel); range.setstart(selrange.endcontainer, selrange.endoffset); remainingtext = range.extractcontents(); $(this).after('<p contenteditable = "true">'+ remainingtext +'</p>'); $(this).next('p').focus(); }
i haven't had success - due lack of understanding when comes range, node , selection objects. able explain how these objects work , how can adapt answer above suit situation.
here's code adapted another answer remove rangy dependency:
var sel = window.getselection(); if (sel.rangecount > 0) { // create copy of selection range work var range = sel.getrangeat(0).clonerange(); // containing paragraph var p = range.commonancestorcontainer; while (p && (p.nodetype != 1 || p.tagname != "p") ) { p = p.parentnode; } if (p) { // place end of range after paragraph range.setendafter(p); // extract contents of paragraph after caret fragment var contentafterrangestart = range.extractcontents(); // collapse range after paragraph range.setstartafter(p); range.collapse(true); // insert content range.insertnode(contentafterrangestart); // move caret insertion point range.setstartafter(p); range.collapse(true); sel.removeallranges(); sel.addrange(range); } }
Comments
Post a Comment