Summary:
I am trying to achieve the effect where when user types a ( or [ in the content-editable div, the second ) or ] is auto-inserted, and the caret be positioned between the two of them, that is, between ( and ).
Type to the right of the --s and see how in the first line it works while doesn't work in the second.
My effort:
I am using this code (by Tim Down) to both highlight some part of text and set cursor position. The former works but latter doesn't :(
function getTextNodesIn(node) { // helper var textNodes = []; if (node.nodeType == 3) { textNodes.push(node); } else { var children = node.childNodes; for (var i = 0, len = children.length; i < len; ++i) { textNodes.push.apply(textNodes, getTextNodesIn(children[i])); } } return textNodes; } function highlightText(el, start, end) { // main if (el.tagName === "DIV") { // content-editable div var range = document.createRange(); range.selectNodeContents(el); var textNodes = getTextNodesIn(el); var foundStart = false; var charCount = 0, endCharCount; for (var i = 0, textNode; textNode = textNodes[i++];) { endCharCount = charCount + textNode.length; if (!foundStart && start >= charCount && (start < endCharCount || (start == endCharCount && i < textNodes.length))) { range.setStart(textNode, start - charCount); foundStart = true; } if (foundStart && end <= endCharCount) { range.setEnd(textNode, end - charCount); break; } charCount = endCharCount; } var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else { // textarea el.selectionStart = start; el.selectionEnd = end; } } Notes:
<div>will have child elements (mostly<br>s).- Only Chrome support required using vanilla JS
My question:
- Why doesn't the above function work?
- How can it be made to work?
I have spent hours searching for this and found nothing much useful. Some were about setting at start or end of a child div but for me it can be any location, anywhere.
UPDATE:
Thanks to everyone is finally finished development!