Last active
January 3, 2022 21:00
-
-
Save mzechmeister/d0333d6e46746efc2f06e61547d69047 to your computer and use it in GitHub Desktop.
pseudo editable field (code mirror lite)
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
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <style> | |
| #cursor { | |
| border-left: 1px solid red; | |
| animation: blink 1s; | |
| margin-left: -1px; | |
| animation-iteration-count: infinite; | |
| } | |
| span { | |
| color: green; | |
| } | |
| span:not(#cursor):before { | |
| content: "5"; | |
| vertical-align: super; | |
| font-size: smaller; | |
| } | |
| @keyframes blink { | |
| 50% { border-color: #ffffff00; } }} | |
| </style> | |
| </head> | |
| <body> | |
| <textarea id="ta" style="height:150px">The top element is a textarea and the div at the bottom a pseudo editable field. Type to see how the caret follows. Type a dollar character to insert a span. Mouse click in the editable field doen't set the caret properly.</textarea> | |
| <div id="mydiv" onclick="ta.selectionEnd = getSelectionPosition(); ta.selectionStart = ta.selectionEnd; ta.focus(); update()"></div> | |
| <script> | |
| function getSelectionPosition() { | |
| var sel = window.getSelection() | |
| console.log(sel) | |
| return sel.focusOffset | |
| } | |
| function parse(t) { | |
| return t.replaceAll('$', '<span>XX</span>') | |
| } | |
| function update() { | |
| curpos = ta.selectionEnd | |
| mydiv.innerHTML = parse(ta.value.slice(0, curpos)+"<span id='cursor'></span>"+ta.value.slice(curpos)) | |
| } | |
| ta.onkeydown = update | |
| ta.oninput = update | |
| ta.onclick = update | |
| ta.onkeyup = update | |
| update() | |
| </script> | |
| </body> | |
| </html> |
Author
Author
To inspect codemirror search for the textarea element and inspect the attached events.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
preview latest: https://gistpreview.github.io/?d0333d6e46746efc2f06e61547d69047
e.inputTypeto detect various events.insText.cutAandcut.divcutselrenamed tocutpos.sel.anchorNodereturnsbodynottain chrome and edge, instead usedocument.activeElement.range.toString().lengthinstead of node loop.fix backward selection (desktop only), double click selection not working
replaceAllnot working on some android, replaced byreplace+/ /g.mousedown+preventDefaultto keep focus on textarea, andrangeParentinstead ofselection. Now, build-in text selection on mobiles does not popup. There seems to be no redundantselectionchangecalls.onselectionchangeinstead of key events. Now pseudo caret is also moved for spacebar swiping on mobiles.onclickdoes not set the caret (firefox).Problems of contenteditable:
document.execCommandanddocument.execCommand+insertHTMLdoes not work.