Last active
November 26, 2023 00:16
-
-
Save islishude/6ccd1fbf42d1eaac667d6873e7b134f8 to your computer and use it in GitHub Desktop.
[DEPRECATED]get/set caret position in contentEditable or textarea/input element(JavaScript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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(_range.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) | |
} | |
} |
Thanks for the breadcrumbs. I put the above stackoverflow snippet with minor modifications into a codepen demo -- I didn't see any problems with <br>
.
Unlike some solutions, it doesn't maintain the selection range, but that's ok for my use case.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@abohomol, I have my own similar solution at https://gist.github.com/Yaffle/117a0f6f92976b5cc6a6f570d911d912 , to handle
It just checks the tagName and considers it is like one new line character.