javascript - Handle caret position in content editable div -
i have content editable div in html
<div contenteditable="true" id="textonlypage"></div> and heres jquery code
var rxp = new regexp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm"); $('#textonlypage').keyup(function(e){ if(e.keycode == 13){ e.preventdefault(); $('#textonlypage').children().each(function() { if ( $(this).is("div") ) { $(this).contents().unwrap(); }}); $('#textonlypage').append("<br/>"); } $('#textonlypage').children().contents().unwrap(); var $this = $(this); var content = $this.html(); $this.html(content.replace(rxp, "<span class='highlight'>$1</span>"));}); problem caret position, because when apply span tags around numbers in string.replace method cursor goes start of content editable div. can't goes next line while press enter key.
i know can handle through range , selection objects, can't find useful resource understand how these objects works.
kindly either provide me solution problem , better if solution in angularjs, or provide me resource can understand range , selection objects working examples.
i faced same issue did while ago, undertand how range , selection works recommend take @ mdn docs selection , range
one reliable way of detecting change in contenteditable div event input. 1 issue found when listenning keyup , preventing default behavior keycode tons of them , it's hard cover use cases.
what prefer let normal event being processed, save caret position, text value , replace parts needs highlighted , set caret position back.
here simple example
var contenteditable = document.queryselector('div[contenteditable]'); contenteditable.addeventlistener('input', oninput); var oninput = function(e) { // function called after current call-stack // finished, @ time user input inserted // in content editable settimeout(function() { // save caret position var text = contenteditable.innertext; // perform replacement on `text` contenteditable.innerhtml = text; // set caret position }, 0); } i wrote 2 handy method getcaretoffsetwithin , setcaretpositionwithin manipulate caret when want perform dom manipulation , re-position caret @ initial value after processing.
you can check them on gist contenteditable-utils.js
Comments
Post a Comment