Last active
March 30, 2022 12:08
-
-
Save foyez/73b62a8dc638e827a6a9fdd132ef1aa7 to your computer and use it in GitHub Desktop.
Set cursor position on clicked location in contenteditable
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
| const getMouseEventCaretRange = (event, doc = document) => { | |
| const x = event.clientX; | |
| const y = event.clientY; | |
| // IE | |
| if (doc.body.createTextRange) { | |
| const range = doc.body.createTextRange(); | |
| range.moveToPoint(x, y); | |
| return range; | |
| } | |
| if (!doc.createRange) { | |
| return null; | |
| } | |
| // standards-based | |
| if (doc.caretPositionFromPoint) { | |
| const pos = doc.caretPositionFromPoint(x, y); | |
| const range = doc.createRange(); | |
| range.setStart(pos.offsetNode, pos.offset); | |
| range.collapse(true); | |
| return range; | |
| } | |
| // firefox | |
| if (typeof event.rangeParent !== "undefined") { | |
| const range = doc.createRange(); | |
| range.setStart(event.rangeParent, event.rangeOffset); | |
| range.collapse(true); | |
| return range; | |
| } | |
| // webkit | |
| if (doc.caretRangeFromPoint) { | |
| return doc.caretRangeFromPoint(x, y); | |
| } | |
| }; | |
| export const setCursorPosition = (event, cWindow = window) => { | |
| const range = getMouseEventCaretRange(event); | |
| if (!range) return; | |
| if (range.select) { | |
| range.select(); | |
| return; | |
| } | |
| const { getSelection } = cWindow || {}; | |
| if (getSelection) { | |
| const selection = getSelection(); | |
| selection.removeAllRanges(); | |
| selection.addRange(range); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment