javascript - Finding the caret position in character in a div content editable with angular -


i m having troubles while getting cursor caret position inside of div contenteditable attribute.

actually, m using following function :

  onblurarea (field, ev) {     ev.preventdefault()     const editable = ev.target.childnodes[1].childnodes[2]     this.positions[field] = {start: this.getcaretcharacteroffsetwithin(editable), editable}   }    getcaretcharacteroffsetwithin (element) {     let ie = (typeof this.doc.selection != 'undefined' && this.doc.selection.type != 'control') && true     let w3 = (typeof this.win.getselection != 'undefined') && true     let caretoffset = 0     if (w3) {       let range = this.win.getselection().getrangeat(0)       console.log(range)       let precaretrange = range.clonerange()       precaretrange.selectnodecontents(element)       precaretrange.setend(range.endcontainer, range.endoffset)       console.log(precaretrange)       caretoffset = precaretrange.tostring().length       console.log(caretoffset)     }     else if (ie) {       let textrange = this.doc.selection.createrange()       let precarettextrange = this.doc.body.createtextrange()       precarettextrange.expand(element)       precarettextrange.setendpoint('endtoend', textrange)       caretoffset = precarettextrange.text.length     }     return caretoffset   } 

the function onblurarea triggered when blur text-angular field :

<text-angular ng-model="modulemanage.currentmodule.description" required ng-blur="modulemanage.onblurarea('description', $event)"></text-angular> 

moreover :

this.doc = $document this.win = $window 
  • i need cursor position add external stuff not managed library.

  • my problem when blur field, carretoffset not same if focus on precise field or on one.

  • the function above gives me 0

  • when log range, m having div item out of current focus, out of text-angular module

edit : think problem on following line :

let range = this.win.getselection().getrangeat(0) 

that give me don't understand @ all...

when blur event fired, u have lost focus , range created.

to caret offset before div lost focus, recommend save caret offset every time changes. say, update every time keyup or mouseup fired or when other timing u update it.

check this plunkr

btw, in plunkr used getcaretcharacteroffsetwithin function calculate offset. function may not working expected. add blanks content , caret offset larger real.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -