Skip to content

Instantly share code, notes, and snippets.

@imolorhe
Forked from islishude/caret.js
Created January 20, 2019 10:37
Show Gist options
  • Save imolorhe/b6ec41233cf7756eeacbb1e38cd42856 to your computer and use it in GitHub Desktop.
Save imolorhe/b6ec41233cf7756eeacbb1e38cd42856 to your computer and use it in GitHub Desktop.
get/set caret position in contentEditable or textarea/input element(JavaScript)
/**
* @file get/set caret position and insert text
* @author islishude
* @license MIT
*/
export class Caret {
/**
* get/set caret position
* @param {HTMLColletion} target
*/
constructor(target) {
this.isContentEditable = target && target.contentEditable
this.target = target
}
/**
* get caret position
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Range}
* @returns {number}
*/
getPos() {
// for contentedit field
if (this.isContentEditable) {
this.target.focus()
let _range = document.getSelection().getRangeAt(0)
let range = _range.cloneRange()
range.selectNodeContents(this.target)
range.setEnd(_rang.endContainer, _range.endOffset)
return range.toString().length;
}
// for texterea/input element
return this.target.selectionStart
}
/**
* set caret position
* @param {number} pos - caret position
*/
setPos(pos) {
// for contentedit field
if (this.isContentEditable) {
this.target.focus()
document.getSelection().collapse(this.target, pos)
return
}
this.target.setSelectionRange(pos, pos)
}
}
/**
* insert text or orther to editor
* @see https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
* @module Editor
*/
export class Editor {
constructor() {
}
/**
* @param {string} content - your insert text
* @returns {boolean}
*/
insertText(content) {
document.execCommand('insertText', false, content)
}
}
@igor-stop
Copy link

Hey! It seems a small mistake at 27 line (_rang)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment