Last active
August 7, 2016 19:10
-
-
Save kvendrik/0c2f1bd01914e6f6edd0215e7e6155f9 to your computer and use it in GitHub Desktop.
es2015 version of insertAtCaret method
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
| function insertAtCaret(text) { | |
| const txtarea = document.activeElement; | |
| const scrollPos = txtarea.scrollTop; | |
| let strPos = 0; | |
| const br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false )); | |
| if (br == "ie") { | |
| txtarea.focus(); | |
| const range = document.selection.createRange(); | |
| range.moveStart('character', -txtarea.value.length); | |
| strPos = range.text.length; | |
| } else if (br == "ff") { | |
| strPos = txtarea.selectionStart; | |
| } | |
| const front = (txtarea.value).substring(0,strPos); | |
| const back = (txtarea.value).substring(strPos,txtarea.value.length); | |
| txtarea.value = front+text+back; | |
| strPos = strPos + text.length; | |
| if (br == "ie") { | |
| txtarea.focus(); | |
| const range = document.selection.createRange(); | |
| range.moveStart ('character', -txtarea.value.length); | |
| range.moveStart ('character', strPos); | |
| range.moveEnd ('character', 0); | |
| range.select(); | |
| } else if (br == "ff") { | |
| txtarea.selectionStart = strPos; | |
| txtarea.selectionEnd = strPos; | |
| txtarea.focus(); | |
| } | |
| txtarea.scrollTop = scrollPos; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment